dynamicly populating a dropdown from a MySQL database

odp123
08:15:10
Hi guys,

I have followed your tutorial on dynamic population of a dropdown menu.

Basically it worked like a charm with one and two dropdown's. But when i add the third menu problems occur. When i load the page, second menu is stuck on the last entry of the subcategory. So it is the same problem formulation as in the dropdown faq-
My page is reloading but second list box is not displaying the matching option

thanks
smo1234
08-16-2010
You can check the demo of three drop down list here.

Watch the URL after selection of second list box. You will have two variables at the query string. Based on this value the first and second drop down list gets locked. In the basic drop down list you can see how the first list box gets locked with the value from the query string, the same technique is used to lock the first and secnd drop down after the selections.

You need to just extend this to more drop down list boxes.
trace7r
09-01-2010
OK, I did use youre 3 dropdown example and totaly raped it (geuss it should be rip it ;-) )
And I'm very new at this stuff so I hope you can and will help me with next problem.

I did change the names of the files:
dd3.php -> stockchecker.php
ddrck.php -> datachecker.php
config.php -> databuilder.php (not used anymore)

I'm just testing this all and wanted to integrate it in a Joomla Component, but I have one problem since I changed the MySQL related stuff, as DB connection and way of handling query's.
Since I changed that all I can load the data from the DB into the dropdown boxes but when I select some in the first or second drop down it refreshes the page and even goes back to the home page...

Can you please help me out?

this is the code for stockchecker.php:
<?php

//***************************************
// This is downloaded from www.plus2net.com //
/// You can distribute this code with the link to www.plus2net.com ///
// Please don't remove the link to www.plus2net.com ///
// This is for your learning only not for commercial use. ///////
//The author is not responsible for any type of loss or problem or damage on using this script.//
/// You can use it at your own risk. /////
//*****************************************

defined('_JEXEC') or die('Restricted access');
// dd3
//require "databuilder.php"; // Your Database details
?>

<!doctype html public "-//w3c//dtd html 3.2//en">

<html>

<head>
<title>Demo of Three Multiple drop down list box</title>
<meta name="GENERATOR" content="Arachnophilia 4.0">
<meta name="FORMATTER" content="Arachnophilia 4.0">
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='stockchecker.php?cat=' + val ;
}
function reload3(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
var val2=form.subcat.options[form.subcat.options.selectedIndex].value;

self.location='stockchecker.php?cat=' + val + '&cat3=' + val2 ;
}

</script>
</head>

<body>
<?
///////// Getting the data from Mysql table for first list box//////////
$db = JFactory::getDBO();
$query2 = "SELECT DISTINCT materiaal FROM #__stock_view";
$db->setQuery( $query2 );
$quer2 = $db->loadResultArray();
///////////// End of query for first list box////////////

/////// for second drop down list we will check if category is selected else we will display all the subcategory/////
$cat=$_GET['cat']; // This line is added to take care if your global variable is off
if(isset($cat) and strlen($cat) > 0){
$query="SELECT DISTINCT merk FROM #__stock_view WHERE materiaal=$cat";
}else{
$query="SELECT DISTINCT merk FROM #__stock_view";
}
$db->setQuery( $query );
$quer = $db->loadResultArray();
////////// end of query for second subcategory drop down list box ///////////////////////////


/////// for Third drop down list we will check if sub category is selected else we will display all the subcategory3/////
$cat3=$_GET['cat3']; // This line is added to take care if your global variable is off
if(isset($cat3) and strlen($cat3) > 0){
$query3="SELECT DISTINCT dikte FROM #__stock_view WHERE merk=$cat3";
}else{
$query3="SELECT DISTINCT dikte FROM #__stock_view";
}
$db->setQuery( $query3 );
$quer3 = $db->loadResultArray();
print_r($quer3);
////////// end of query for third subcategory drop down list box ///////////////////////////

echo "<form method=post name=f1 action='datachecker.php'>";
////////// Starting of first drop downlist /////////
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Selecteer het materiaal</option>";
foreach($quer2 as $key => $value){
echo "<option value=$key>$value</option>";
}
echo "</select>";
////////////////// This will end the first drop down list ///////////

////////// Starting of second drop downlist /////////
echo "<select name='subcat' onchange=\"reload3(this.form)\"><option value=''>Selecteer het merk</option>";
foreach($quer as $key => $value){
echo "<option value=$key>$value</option>";
}
echo "</select>";
////////////////// This will end the second drop down list ///////////

////////// Starting of third drop downlist /////////
echo "<select name='subcat3' ><option value=''>Selecteer de dikte</option>";
foreach($quer3 as $key => $value){
echo "<option value=$key>$value</option>";
}
echo "</select>";
////////////////// This will end the third drop down list ///////////

echo "<input type=submit value='Submit the form data'></form>";
?>

</body>

</html>


This is the code for datachecker.php:

<?php

//***************************************
// This is downloaded from www.plus2net.com //
/// You can distribute this code with the link to www.plus2net.com ///
// Please don't remove the link to www.plus2net.com ///
// This is for your learning only not for commercial use. ///////
//The author is not responsible for any type of loss or problem or damage on using this script.//
/// You can use it at your own risk. /////
//*****************************************

defined('_JEXEC') or die('Restricted access');
//dd3ck
?>

<!doctype html public "-//w3c//dtd html 3.2//en">

<html>

<head>
<title>Multiple drop down list box from plus2net</title>
<meta name="GENERATOR" content="Arachnophilia 4.0">
<meta name="FORMATTER" content="Arachnophilia 4.0">
</head>

<body>
<?

$cat=$_POST['cat'];
$subcat=$_POST['subcat'];
$subcat3=$_POST['subcat3'];

echo " cat=$cat <br> subcat=$subcat <br> subcat3= $subcat3 ";

?>

</body>

</html>


There is no code for databuilder.php, can be used when I split all data again so js and query's will be put in another file.
But first wanna get it to work this way.

You can find the result at http://onzewijk.be/IK/index.php?option=com_stockchecker

I fully understand that the problem is all mine but I can't find the solution at this moment for it.
Maybe it is just because I don't use the mysql commands...

Greetings Trace7r.
smo1234
09-02-2010
It is working now. I think you fixed the problem.
trace7r
09-02-2010
Yep I did, totally ripped the first code and build it up again, greatest mistake was that I forgot to compare with the selection on buildup of selectbox, if someone is interested in the code as I made it, feel free to ask and then I will post...

Greetings Trace7r.
trace7r
09-07-2010
Again I did change the code so it would be real AJAX and the page wont refresh anymore, but I have ONE BIG PROBLEM... It works in Google Chrome and in Safari but not in IE and firefox, can someone help me with it???
Did try to change the $_GET to $_POST but that didnt seem to work... every reaction is welcome...

code for stockchecker.php

<?php
defined('_JEXEC') or die('Restricted access');

$link_path = substr(JPATH_COMPONENT, strlen(JPATH_ROOT)+1);
require "config.php"; // Your Database details
require "stockchecker.js"; // Your JS/Ajax code
?>

<!doctype html public "-//w3c//dtd html 3.2//en">

<html>

<head>
<title>Stock Checker</title>
<meta name="GENERATOR" content="Arachnophilia 4.0">
<meta name="FORMATTER" content="Arachnophilia 4.0">

<style type="text/css">
<!--
SELECT {
background-color: black;
border-color: black;
color: yellow;
font-family: arial, verdana, ms sans serif;
font-weight: bold;
font-size: 12pt;
}
TEXTAREA {
background-color: black;
color: yellow;
font-family: arial, verdana, ms sans serif;
font-weight: bold;
font-size: 12pt;
text-align: center
}
TABLE {
background-color: black;
color: yellow;
border-color: yellow;
font-family: arial, verdana, ms sans serif;
font-weight: bold;
font-size: 12pt;
text-align: left
}
-->
</style>

<!-- AJAX BEGIN -->



<!-- AJAX EINDE -->

</head>

<body>
<table border="1px" width="100%" aligen="center">
<tr>
<td width="50%">
Selecteer het materiaal
</td>
<td width="50%">
<select name="drop1" id="drop1" onchange="display_data(this.id);" >
<option>Selecteer...</option-->
<?php
$query="select distinct materiaal from jo2_stock_view";
$result=mysql_query($query);
while(list($name)=mysql_fetch_row($result)) {
echo "<option value=\"".$name."\">".$name."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td width="50%">
Selecteer het merk
</td>
<td width="50%">
<select name="drop2" id="drop2" onchange="display_data(this.id);" style=visibility:hidden>
<option>Selecteer...</option>
</select>
</td>
</tr>
<tr>
<td width="50%">
Selecteer de dikte
<td width="50%">
<select name="drop3" id="drop3" onchange="display_data(this.id);" style=visibility:hidden>
<option>Selecteer...</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
In Opbouw!
</td>
</tr>
</table>
<div id="employ_data"></div>


</body>

</html>


code for stockchecker.js
<script language="JavaScript" type="text/javascript">

<!--
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}

// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
var precombo = document.getElementById(window.thisDrop);
var combo = document.getElementById(window.nextDrop);
var lastcombo = document.getElementById('drop3');
if (precombo == drop1){
combo.disabled=false;
combo.style.visibility='visible';
lastcombo.style.visibility='hidden';
}else{
precombo.disabled=true;
combo.disabled=false;
combo.style.visibility='visible';
}

combo.options.length = 0;

var response = httpObject.responseText;
var items = response.split(";");
var count = items.length;
for (var i=0;i<count;i++){
var options = items[i].split("-");
combo.options[i] =
new Option(options[0],options[1]);
}
}
}

// Implement business logic
function display_data(drop){
window.thisDrop=drop;
var name=drop.match(/[^\d]/g).join('');
var number=drop.match(/\d/g).join('');
if (number == 3){
var firstcombo = document.getElementById('drop1');
firstcombo.disabled=false;
firstcombo.style.visibility='visible';
}
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "components/com_stockchecker/databuilder.php?"
+"dropnr=" + number
+"&selection="+document.getElementById(name+number).value,true);
httpObject.onreadystatechange = setOutput;
httpObject.send(null);

}
number++;
window.nextDrop=name+number;
}

var httpObject = null;

//-->

</script>


code for databuilder.php
<?php

require "config.php"; // Your Database details
$Selection = $_GET['selection']; // This line is added to take care if your global variable is off
$Dropnr = $_GET['dropnr']; // This line is added to take care if your global variable is off

if (isset($Selection) && isset($Dropnr)) {

switch($Dropnr){

case 1:
if ($Selection!="Selecteer..."){
$query="select distinct merk from jo2_stock_view where materiaal='$Selection'";
$result=mysql_query($query);
$merk="Selecteer...";
while($mysqlresult=mysql_fetch_array($result)){
if($merk==""){
$merk=$mysqlresult['merk'];
}else{
$merk=$merk.";".$mysqlresult['merk'];
}
}
echo ($merk);
}else{
echo "Selecteer...";
}
break;

case 2:
if ($Selection!="Selecteer..."){
$query="select distinct dikte from jo2_stock_view where merk='$Selection'";
$result=mysql_query($query);
$dikte="Selecteer...";
while($mysqlresult=mysql_fetch_array($result)){
if($dikte==""){
$dikte=$mysqlresult['dikte'];
}else{
$dikte=$dikte.";".$mysqlresult['dikte'];
}
}
echo ($dikte);
}else{
echo "Selecteer...";
}
break;

case 3:

break;

default:

echo $Dropnr;

}

}else{
echo "Verkeerde selectie!";
}
?>


code for config.php
<?php

mysql_connect('mysqlhost','username','password');
mysql_select_db('dbname');

?>


code for datachecker.php
<?php

//***************************************
// This is downloaded from www.plus2net.com //
/// You can distribute this code with the link to www.plus2net.com ///
// Please don't remove the link to www.plus2net.com ///
// This is for your learning only not for commercial use. ///////
//The author is not responsible for any type of loss or problem or damage on using this script.//
/// You can use it at your own risk. /////
//*****************************************

defined('_JEXEC') or die('Restricted access');
//dd3ck
?>

<!doctype html public "-//w3c//dtd html 3.2//en">

<html>

<head>
<title>Multiple drop down list box from plus2net</title>
<meta name="GENERATOR" content="Arachnophilia 4.0">
<meta name="FORMATTER" content="Arachnophilia 4.0">
</head>

<body>
<?

$cat=$_POST['cat'];
$subcat=$_POST['subcat'];
$subcat3=$_POST['subcat3'];

echo " cat=$cat <br> subcat=$subcat <br> subcat3= $subcat3 ";

?>

</body>

</html>


please some help or some tips would be nice :)

Greetings trace7r.


smo1234
09-07-2010
You need to address all browsers while creating xml http object for Ajax. Check this link http://www.plus2net.com/php_tutorial/ajax-get.php

This is what I saw first, there may be other things.
trace7r
09-13-2010
Did change and clean some code...

stockchecker.php:
<?php
defined('_JEXEC') or die('Restricted access');

$link_path = substr(JPATH_COMPONENT, strlen(JPATH_ROOT)+1);
require "config.php"; // Your Database details
require "stockchecker.js"; // Your JS/Ajax code
?>

<!doctype html public "-//w3c//dtd html 3.2//en">

<html>

<head>
<title>Stock Checker</title>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<!--meta name="GENERATOR" content="Arachnophilia 4.0">
<meta name="FORMATTER" content="Arachnophilia 4.0"-->

<style type="text/css">
<!--
SELECT {
background-color: black;
border-color: black;
color: yellow;
font-family: arial, verdana, ms sans serif;
font-weight: bold;
font-size: 12pt;
}
TEXTAREA {
background-color: black;
color: yellow;
font-family: arial, verdana, ms sans serif;
font-weight: bold;
font-size: 12pt;
text-align: center
}
TABLE {
background-color: black;
color: yellow;
border-color: yellow;
font-family: arial, verdana, ms sans serif;
font-weight: bold;
font-size: 12pt;
text-align: left
}

-->
</style>

<!-- AJAX BEGIN -->



<!-- AJAX EINDE -->

</head>

<body>
<form name="frm" id="frm">

<table border="1px" width="400px" align="center">
<tr>
<td width="50%">
Selecteer het materiaal
</td>
<td width="50%">
<select name="drop1" id="drop1" onchange="display_data(this.id);" >
<option>Selecteer...</option>
<?php
$query="select distinct materiaal from jo2_stock_view";
$result=mysql_query($query);
while(list($name)=mysql_fetch_row($result)) {
echo "<option value=\"".$name."\">".$name."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td width="50%">
Selecteer het merk
</td>
<td width="50%">
<select name="drop2" id="drop2" onchange="display_data(this.id);">
<option>Selecteer...</option>
</select>
</td>
</tr>
<tr>
<td width="50%">
Selecteer de dikte
</td>
<td width="50%">
<select name="drop3" id="drop3" onchange="display_data(this.id);">
<option>Selecteer...</option>
</select>
</td>
</tr>
<tr>
<td width="50%">
Selecteer Test
</td>
<td width="50%">
<select name="drop4" id="drop4" onchange="display_data(this.id);">
<option>Selecteer...</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtbox" id="txtbox" cols="90" rows="2" align="center"></textarea>
</td>
</tr>
</table>

</form>


</body>

</html>


stockchecker.js:
<script language="JavaScript" type="text/javascript">

// Get the HTTP Object
function getHTTPObject(){
var C=null;
try {
C=new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e) {
try{
C=new ActiveXObject("Microsoft.XMLHTTP")
}
catch(sc) {
C=null
}
}
if(!C && typeof XMLHttpRequest!="undefined") {
C=new XMLHttpRequest()
}
return C;
}

// Change the value of the outputfield
function setOutput(){
if(httpObject.readyState == 4){
var comb1 = document.getElementById('drop1');
var comb2 = document.getElementById('drop2');
var comb3 = document.getElementById('drop3');
var comb4 = document.getElementById('drop4');
var precombo = document.getElementById(window.thisDrop);
var combo = document.getElementById(window.nextDrop);
var txtbox = document.getElementById('txtbox');
var lastcombo = 'drop4';

var response = httpObject.responseText;
var items = response.split(";");
var count = items.length;

//combo.options.length=0;

for (var i=0;i<count;i++){
var options = items[i].split("-");
combo.options[i]=new Option(options[0],options[1]);
}

switch (precombo.id){ case 'drop1':
combo.disabled=false;
txtbox.innerHTML="1";
break;
case 'drop2':
precombo.disabled=true;
combo.disabled=false;
txtbox.innerHTML="2";
break;
case 'drop3':
precombo.disabled=true;
combo.disabled=false;
txtbox.innerHTML="3";
break;
case 'drop4':
precombo.disabled=true;
document.frm.txtbox.innerHTML='U heeft gekozen voor '+comb1.value.toUpperCase()
+' van het merk '+comb2.value.toUpperCase()
+ '\n'
+' met een dikte van '+comb3.value+' cm.';
break;
}
}
}

// Implement business logic
function display_data(drop){ window.thisDrop=name+number;
var name=drop.match(/[^\d]/g).join('');
var number=drop.match(/\d/g).join('');
window.thisDrop=drop;

httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "components/com_stockchecker/databuilder.php?"
+"dropnr=" + number
+"&selection="+document.getElementById(name+number).value,true);
httpObject.onreadystatechange = setOutput;
httpObject.send(null);

}
if (number ==4){ self.location= precombo.id;
}
number++;
window.nextDrop=name+number;
}

var httpObject = null;

</script>



Have tried to debug soms stuff and did get next message from IE...

object requested with a link to next line :

combo.options.length=0;


When I comment that line I get the same message but on following line:

combo.options[i]=new Option(options[0],options[1]);


But the big question stil is, why is it working in safari and chrome and NOT in IE and FireFox...

Greetz Trace7r, hope someone will and can help me...
link to the code http://onzewijk.be/IK/index.php?option=com_stockchecker
trace7r
09-13-2010
OK I solved a part of this problem...
In the code you find next lines:
number++;
window.nextDrop=name+number;

Back at the end of the code, but a few lines up I call the function setOuput were I do use
window.nextDrop
so I just made a real stupid mistake...

I moved the lines up so I get:
number++;
window.nextDrop=name+number;
httpObject.onreadystatechange = setOutput;
httpObject.send(null);

and IE and FF are working a little better now... Another problem, propebly as stupid as this one, is not getting filled of the 3rd combo in IE and FF...
Reason unknown yet...

So feel free to help me find my next mistake :-S
greetz Trace7r.
Please Login to post your reply or start a new topic