Author Topic: Dynamic DropDown PHP/AJAX  (Read 80306 times)

0 Members and 1 Guest are viewing this topic.

Offline MadTechieTopic starter

  • Guru
  • Freak!
  • *
  • Posts: 9,374
  • Gender: Male
  • I try to F1
    • View Profile
Dynamic DropDown PHP/AJAX
« on: August 21, 2007, 12:50:18 PM »
OK, this isn't a request, but many have asked for this sort of thing so i thought i'll write one
please read the comments

if their is anything thats doesn't make sense please let me know and i'll try to explain better..

this all works as one file..

first off, this snipplet of code was written to emulate a database
Code: [Select]
$NewData = "";
$P = (int)$_GET['Param'];

//Emulate the database
$DB[1][] = "NewItem1 - 1";
$DB[1][] = "NewItem1 - 2";

$DB[2][] = "NewItem2 - 1";
$DB[2][] = "NewItem2 - 2";

//Emulate the select
$row = $DB[$P];

//use contents from DB to build the Options
foreach($row as $K1 => $V1)
{
$NewData .= "<option value='$K1'>$V1</option>\n";
}

you can replace that with

Code: [Select]
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("first_test",$dbh)
if (!mysql_query("SELECT * FROM table WHERE ID=$P"))
{
  echo "Database is down";
}
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
   $NewData .= "<option value='".$row['ID']."'>".$row['Name']."</option>\n";
}
mysql_close($dbh);


TRY this by itself first.. (single file)
Code: [Select]
<?php
//for use with my FIRST list box
$list1[1] = "Item1";
$list1[2] = "Item2";

if( isset($_GET['Param']) )
{
$NewData "";
$P = (int)$_GET['Param'];

//Emulate the database
$DB[1][] = "NewItem1 - 1";
$DB[1][] = "NewItem1 - 2";

$DB[2][] = "NewItem2 - 1";
$DB[2][] = "NewItem2 - 2";

//Emulate the select
$row $DB[$P];

//use contents from DB to build the Options
foreach($row as $K1 => $V1)
{
$NewData .= "<option value='$K1'>$V1</option>\n";
}
echo $NewData//Send Data back
exit; //we're finished so exit..
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Simple Dymanic Drop Down</title>
<script language="javascript">


function ajaxFunction(ID, Param)
{
//link to the PHP file your getting the data from
//var loaderphp = "register.php";
//i have link to this file
var loaderphp = "<?php echo $_SERVER['PHP_SELF'?>";

//we don't need to change anymore of this script
var xmlHttp;
try
    {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
    }catch(e){
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
    xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
        {
document.getElementById(ID).innerHTML = xmlHttp.responseText;
        }
}
    xmlHttp.open("GET", loaderphp+"?Param="+Param,true);
    xmlHttp.send(null);
}
</script>

</head>
<body>

<!-- OK a basic form-->
<form method="post" enctype="multipart/form-data" name="myForm" target="_self">
<table border="0">
  <tr>
    <td>
<!--
OK here we call the ajaxFuntion LBox2 refers to where the returned date will go
and the this.value will be the value of the select option
-->
<select name="list1" onchange="ajaxFunction('LBox2', this.value);">
<option value=''></option>
<?php 
foreach($list1 as $K1 => $V1)
{
echo "<option value='$K1'>$V1</option>";
}
?>

</select>
</td>
    <td>
<select name="list2" id="LBox2">
<!-- OK the ID of this list box is LBox2 as refered to above -->
</select>
</td>
  </tr>
</table>
  <input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>

« Last Edit: August 21, 2007, 12:56:41 PM by MadTechie »
Computers are good at following instructions, but not at reading your mind.
The quality of a response, is usually directly related to the quality of the question. ©2009 mjdamato
I dunno about that.  A regular expression has a 0% chance of touching my penis.
the code is professionally made up but not working
Remember to Click Solved, how to ask questions - the smart way

Offline MadTechieTopic starter

  • Guru
  • Freak!
  • *
  • Posts: 9,374
  • Gender: Male
  • I try to F1
    • View Profile
Re: Dynamic DropDown PHP/AJAX
« Reply #1 on: January 18, 2009, 07:25:52 PM »
Due to a few PM's asking for a third box or example for the SQL side i have decided to update the script, i have tried to keep it simple.. i have include the SQL table structure and some sample data.. i hope it helps


Code: [Select]
<?php
/*
-- SQL Data
--
-- Table structure for table `list1`
--

CREATE TABLE `list1` (
  `ID` mediumint(8) NOT NULL auto_increment,
  `Name` varchar(15) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Dumping data for table `list1`
--

INSERT INTO `list1` (`ID`, `Name`) VALUES
(1, 'Dogs'),
(2, 'Trees'),
(3, 'Apples');

-- --------------------------------------------------------

--
-- Table structure for table `list2`
--

CREATE TABLE `list2` (
  `ID` mediumint(8) NOT NULL auto_increment,
  `List1Ref` mediumint(8) NOT NULL,
  `Name` varchar(20) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `list2`
--

INSERT INTO `list2` (`ID`, `List1Ref`, `Name`) VALUES
(1, 1, 'Sleep in'),
(2, 1, 'Bark at'),
(3, 2, 'Grow'),
(4, 2, 'Are'),
(5, 3, 'are coloured'),
(6, 3, 'Taste');

-- --------------------------------------------------------

--
-- Table structure for table `list3`
--

CREATE TABLE `list3` (
  `ID` mediumint(8) NOT NULL auto_increment,
  `List2Ref` mediumint(8) NOT NULL,
  `Name` varchar(20) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

--
-- Dumping data for table `list3`
--

INSERT INTO `list3` (`ID`, `List2Ref`, `Name`) VALUES
(1, 1, 'Baskets'),
(2, 1, 'on the couch'),
(3, 2, 'Cats'),
(4, 2, 'Postmen'),
(5, 3, 'slowly'),
(6, 4, 'green'),
(7, 5, 'Red'),
(8, 5, 'Green'),
(9, 6, 'Nice'),
(10, 6, 'Not nice');


*/
$hostname "localhost";
$username "root";
$password "";

?>


<?php
$dbh mysql_connect($hostname$username$password)
or die("Unable to connect to MySQL");
$selected mysql_select_db("ajax_test",$dbh);
   
if( isset($_POST['Submit']) )
   
{
   
echo "<pre>";
   
print_r($_POST);
   
}
   
if( isset($_GET['ajax']) )
{
//In this if statement
switch($_GET['ID'])
{
case "LBox2":
$query sprintf("SELECT * FROM list2 WHERE List1Ref=%d",$_GET['ajax']);
break;
case "LBox3":
$query sprintf("SELECT * FROM list3 WHERE List2Ref=%d",$_GET['ajax']);
break;
}

$result mysql_query($query);
echo "<option value=''></option>";
while ($row mysql_fetch_assoc($result))
{
echo "<option value='{$row['ID']}'>{$row['Name']}</option>\n";
}
mysql_close($dbh);
exit; //we're finished so exit..
}

if (!$result mysql_query("SELECT * FROM list1"))
{
echo "Database is down";
}
//for use with my FIRST list box
$List1 "";
while ($row mysql_fetch_assoc($result))
{
$List1 .= "<option value='{$row['ID']}'>{$row['Name']}</option>\n";
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Simple Dymanic Drop Down</title>
<script language="javascript">
function ajaxFunction(ID, Param)
{
   //link to the PHP file your getting the data from
   //var loaderphp = "register.php";
   //i have link to this file
   var loaderphp = "<?php echo $_SERVER['PHP_SELF'?>";
   
   //we don't need to change anymore of this script
   var xmlHttp;
   try
    {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
    }catch(e){
      // Internet Explorer
      try
      {
         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }catch(e){
         try
         {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
         }catch(e){
            alert("Your browser does not support AJAX!");
            return false;
         }
      }
   }
   
   xmlHttp.onreadystatechange=function()
   {
      if(xmlHttp.readyState==4)
        {
        //the line below reset the third list box incase list 1 is changed
        document.getElementById('LBox3').innerHTML = "<option value=''></option>";
       
        //THIS SET THE DAT FROM THE PHP TO THE HTML
document.getElementById(ID).innerHTML = xmlHttp.responseText;
        }
   }
    xmlHttp.open("GET", loaderphp+"?ID="+ID+"&ajax="+Param,true);
    xmlHttp.send(null);
}
</script>
</head>
<body>
<!-- OK a basic form-->
<form method="post" enctype="multipart/form-data" name="myForm" target="_self">
<table border="0">
  <tr>
    <td>
      <!--
      OK here we call the ajaxFuntion LBox2 refers to where the returned date will go
      and the this.value will be the value of the select option
      -->
      <select name="list1" id="LBox1" onchange="ajaxFunction('LBox2', this.value);">
         <option value=''></option>
      <?php 
         
echo $List1;
      
?>

      </select>
   </td>
    <td>
      <select name="list2" id="LBox2" onchange="ajaxFunction('LBox3', this.value);">
      <option value=''></option>
            <!-- OK the ID of this list box is LBox2 as refered to above -->
      </select>
   </td>
   <td>
      <select name="list3" id="LBox3">
      <option value=''></option>
            <!-- OK the ID of this list box is LBox3 Same as above -->
      </select>
   </td>
  </tr>
</table>
  <input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>



Same as above without MySQL
Code: [Select]
<?php
   
if( isset($_GET['ajax']) )
   {
      
//In this if statement
      
switch($_GET['ID'])
      {
         case 
"LBox2":
            
$Data[1] = array(10=>"-Tom"20=>"Jimmy"); 
            
$Data[2] = array(30=>"Bob"40=>"-MadTechie");
            
$Data[3] = array(50=>"-One"60=>"Two");
         break;
         
         
//Only added values for -Tom, -MadTechie and -One (10,40,50)
         
case "LBox3":
            
$Data[10] = array(100=>"One 00"200=>"Two 00");
            
$Data[40] = array(300=>"Three 00");
            
$Data[50] = array(1000=>"10000");
         break;
      }
      
      echo 
"<option value=''></option>";
      foreach(
$Data[$_GET['ajax']] as $K => $V)
      {
         echo 
"<option value='$K'>$V</option>\n";
      }
      
mysql_close($dbh);
      exit; 
//we're finished so exit..
   
}
   
$Data = array(1=>"One"2=>"Two"3=>"Three");
   
$List1 "<option value=''></option>";
   foreach(
$Data as $K => $V)
   {
      
$List1 .= "<option value='$K'>$V</option>\n";
   }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Simple Dymanic Drop Down</title>
<script language="javascript">
   function ajaxFunction(ID, Param)
   {
      //link to the PHP file your getting the data from
      //var loaderphp = "register.php";
      //i have link to this file
      var loaderphp = "<?php echo $_SERVER['PHP_SELF'?>";
     
      //we don't need to change anymore of this script
      var xmlHttp;
      try
       {
         // Firefox, Opera 8.0+, Safari
         xmlHttp=new XMLHttpRequest();
       }catch(e){
         // Internet Explorer
         try
         {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
         }catch(e){
            try
            {
               xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){
               alert("Your browser does not support AJAX!");
               return false;
            }
         }
      }
     
      xmlHttp.onreadystatechange=function()
      {
         if(xmlHttp.readyState==4)
           {
              //the line below reset the third list box incase list 1 is changed
              document.getElementById('LBox3').innerHTML = "<option value=''></option>";
             
              //THIS SET THE DAT FROM THE PHP TO THE HTML
            document.getElementById(ID).innerHTML = xmlHttp.responseText;
           }
      }
       xmlHttp.open("GET", loaderphp+"?ID="+ID+"&ajax="+Param,true);
       xmlHttp.send(null);
   }
</script>
</head>
<body>
<!-- OK a basic form-->
<form method="post" enctype="multipart/form-data" name="myForm" target="_self">
<table border="0">
  <tr>
    <td>
      <!--
      OK here we call the ajaxFuntion LBox2 refers to where the returned date will go
      and the this.value will be the value of the select option
      -->
      <select name="list1" id="LBox1" onchange="ajaxFunction('LBox2', this.value);">
      <?php 
         
echo $List1;
      
?>

      </select>
   </td>
    <td>
      <select name="list2" id="LBox2" onchange="ajaxFunction('LBox3', this.value);">
         <option value=''></option>
            <!-- OK the ID of this list box is LBox2 as refered to above -->
      </select>
   </td>
   <td>
      <select name="list3" id="LBox3">
         <option value=''></option>
            <!-- OK the ID of this list box is LBox3 Same as above -->
      </select>
   </td>
  </tr>
</table>
  <input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>

« Last Edit: February 26, 2009, 03:30:41 PM by MadTechie »
Computers are good at following instructions, but not at reading your mind.
The quality of a response, is usually directly related to the quality of the question. ©2009 mjdamato
I dunno about that.  A regular expression has a 0% chance of touching my penis.
the code is professionally made up but not working
Remember to Click Solved, how to ask questions - the smart way

Offline MadTechieTopic starter

  • Guru
  • Freak!
  • *
  • Posts: 9,374
  • Gender: Male
  • I try to F1
    • View Profile
Re: Dynamic DropDown PHP/AJAX
« Reply #2 on: October 09, 2009, 08:53:09 PM »
Okay.. first off this is more of a hack, I will re-write this whole thing correctly but for now

I have received quite a few PM's telling me that the code above doesn't work in IE8
this is true, it due to the use of innerHTML, Now normally I would use JSON to pass arrays between PHP & JS but as i have stated this is just a quick hack,

if your updating code then the only real change is the 20 lines below
Code: [Select]
if(xmlHttp.readyState==4)(lines 159-179)

Now what is does it rebuild the dropdown box, using a Regular Expression to extra the options data from the html passed back from PHP,

Hope it helps :)

Code: [Select]
<?php
/*
-- SQL Data
--
-- Table structure for table `list1`
--

CREATE TABLE `list1` (
  `ID` mediumint(8) NOT NULL auto_increment,
  `Name` varchar(15) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Dumping data for table `list1`
--

INSERT INTO `list1` (`ID`, `Name`) VALUES
(1, 'Dogs'),
(2, 'Trees'),
(3, 'Apples');

-- --------------------------------------------------------

--
-- Table structure for table `list2`
--

CREATE TABLE `list2` (
  `ID` mediumint(8) NOT NULL auto_increment,
  `List1Ref` mediumint(8) NOT NULL,
  `Name` varchar(20) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `list2`
--

INSERT INTO `list2` (`ID`, `List1Ref`, `Name`) VALUES
(1, 1, 'Sleep in'),
(2, 1, 'Bark at'),
(3, 2, 'Grow'),
(4, 2, 'Are'),
(5, 3, 'are coloured'),
(6, 3, 'Taste');

-- --------------------------------------------------------

--
-- Table structure for table `list3`
--

CREATE TABLE `list3` (
  `ID` mediumint(8) NOT NULL auto_increment,
  `List2Ref` mediumint(8) NOT NULL,
  `Name` varchar(20) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

--
-- Dumping data for table `list3`
--

INSERT INTO `list3` (`ID`, `List2Ref`, `Name`) VALUES
(1, 1, 'Baskets'),
(2, 1, 'on the couch'),
(3, 2, 'Cats'),
(4, 2, 'Postmen'),
(5, 3, 'slowly'),
(6, 4, 'green'),
(7, 5, 'Red'),
(8, 5, 'Green'),
(9, 6, 'Nice'),
(10, 6, 'Not nice');


*/
   
$hostname "localhost";
   
$username "root";
   
$password "";

?>


<?php
   $dbh 
mysql_connect($hostname$username$password)
      or die(
"Unable to connect to MySQL");
   
$selected mysql_select_db("ajax_test",$dbh);
   if( isset(
$_GET['ajax']) )
   {
      
//In this if statement
      
switch($_GET['ID'])
      {
         case 
"LBox2":
            
$query sprintf("SELECT * FROM list2 WHERE List1Ref=%d",$_GET['ajax']);
         break;
         case 
"LBox3":
            
$query sprintf("SELECT * FROM list3 WHERE List2Ref=%d",$_GET['ajax']);
         break;
      }
      
      
$result mysql_query($query) or die(mysql_error());
      while (
$row mysql_fetch_assoc($result))
      {
         echo 
"<option value='{$row['ID']}'>{$row['Name']}</option>\n";
      }
      
mysql_close($dbh);
      exit; 
//we're finished so exit..
   
}
   
   if (!
$result mysql_query("SELECT * FROM list1"))
   {
      echo 
"Database is down";
   }
   
//for use with my FIRST list box
   
$List1 "";
   while (
$row mysql_fetch_assoc($result))
   {
      
$List1 .= "<option value='{$row['ID']}'>{$row['Name']}</option>\n";
   }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Simple Dymanic Drop Down</title>
<script language="javascript">
   function ajaxFunction(ID, Param)
   {
      //link to the PHP file your getting the data from
      //var loaderphp = "register.php";
      //i have link to this file
      var loaderphp = "<?php echo $_SERVER['PHP_SELF'?>";
     
      //we don't need to change anymore of this script
      var xmlHttp;
      try
       {
         // Firefox, Opera 8.0+, Safari
         xmlHttp=new XMLHttpRequest();
       }catch(e){
         // Internet Explorer
         try
         {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
         }catch(e){
            try
            {
               xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){
               alert("Your browser does not support AJAX!");
               return false;
            }
         }
      }
     
      xmlHttp.onreadystatechange=function()
      {
         if(xmlHttp.readyState==4)
           {
              //the line below reset the third list box incase list 1 is changed
              var sSelect = document.getElementById(ID);
for(options in sSelect.options) sSelect.remove(options);
              var opt = document.createElement("option");
sSelect.options.add(opt);
var data = xmlHttp.responseText;

results = data.split('\n');
for(r in results){
var d =  results[r];
match = d.match(/<option value='(.*?)'>([^<]*)<\/option>/);
if (match != null) {
var opt = document.createElement("option");
opt.value= match[1];
opt.text = match[2];
sSelect.options.add(opt);
}
}
           }
      }
       xmlHttp.open("GET", loaderphp+"?ID="+ID+"&ajax="+Param,true);
       xmlHttp.send(null);
   }
</script>
</head>
<body>
<!-- OK a basic form-->
<form method="post" enctype="multipart/form-data" name="myForm" target="_self">
<table border="0">
  <tr>
    <td>
      <!--
      OK here we call the ajaxFuntion LBox2 refers to where the returned date will go
      and the this.value will be the value of the select option
      -->
      <select name="list1" id="LBox1" onchange="ajaxFunction('LBox2', this.value);">
         <option value=''></option>
      <?php 
         
echo $List1;
      
?>

      </select>
   </td>
    <td>
      <select name="list2" id="LBox2" onchange="ajaxFunction('LBox3', this.value);">
         <option value=''></option>
            <!-- OK the ID of this list box is LBox2 as refered to above -->
      </select>
   </td>
   <td>
      <select name="list3" id="LBox3">
         <option value=''></option>
            <!-- OK the ID of this list box is LBox3 Same as above -->
      </select>
   </td>
  </tr>
</table>
  <input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>

any problems feel free to PM me
« Last Edit: October 09, 2009, 09:08:44 PM by MadTechie »
Computers are good at following instructions, but not at reading your mind.
The quality of a response, is usually directly related to the quality of the question. ©2009 mjdamato
I dunno about that.  A regular expression has a 0% chance of touching my penis.
the code is professionally made up but not working
Remember to Click Solved, how to ask questions - the smart way