Jump to content

Cascading Ajax Dropdown


sullyman

Recommended Posts

Hi folks,

 

followed the cascading ajax dropdown in the tutorials section here on the forum and managed to get it working on a test page located here - http://www.fixytips.com/test1.php

 

How can i now show a result (to be located underneath the dropdown selections) after clicking submit?

 

The only easy example i can think of what am i trying to achieve relates to cars.

 

(e.g. if first drop down was Make(ford), second drop down was Model (Fiesta), and third drop down was Size (2.0L), how can i show a list of cars then for that selection underneath)

 

Any help or examples appreciated

S

Link to comment
Share on other sites

<script type="text/javascript">
var modelSelect = document.getElementById('model');
var sizeSelect = document.getElementById('size');
function enableModel() {
    if (modelSelect.disabled) modelSelect.disabled = false;
    //perform Ajax query, fill select with data
}

function enableSize() {
    if (sizeSelect.disabled) sizeSelect.disabled = false;
    //perform Ajax query, fill select with data
}
</script>

<select id="make" name="make" onchange="javascript:enableModel();">
..

<select id="model" name="model" onchange="javascript:enableSize();" disabled="disabled">
..

Link to comment
Share on other sites

Well, you will need to have a database that holds all of those products/classifications that you can query against.

 

Then...after the selections are made in the dropdown, you would create your MySQL query based off of those parameters.

 

Say in your example, the select boxes posted the following...

 

$_POST['make'] = "ford"

$_POST['model'] = "fiesta"

$_POST['size'] = "2.0L"

 

You would have a query that did something similar to this.

 

<?php

foreach($_POST as $key=>$value){
$_POST[$key] = mysql_real_escape_string($value);
}

$sql = "SELECT * from cars where make = '".$_POST['make']."' AND model ='".$_POST['model']."' AND size = '".$_POST['size']."'"

 

Link to comment
Share on other sites

Thanks folks - I changed the values in my db to make, model, size etc. so i can try and follow on from the example. Unfortunately, the size dropdown is not working now.

 

The DB is structured as follows:

List1 (Table)

Id

Make

 

List2 (Table)

Id

Listref1

Model

 

List3 (Table)

Id

Listref2

Size

 

 

<?php
   $dbh = mysql_connect($hostname, $username, $password)
      or die("Unable to connect to MySQL");
   $selected = mysql_select_db($dbname,$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['Model']}</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['Make']}</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>

Link to comment
Share on other sites

P.S. I will make another table Cars to hold a few test records so i can show them listed after the person hits submit

 

Is this code all i have to place on my page;

 

<?php

foreach($_POST as $key=>$value){
$_POST[$key] = mysql_real_escape_string($value);
}

$sql = "SELECT * from cars where make = '".$_POST['make']."' AND model ='".$_POST['model']."' AND size = '".$_POST['size']."'"

Link to comment
Share on other sites

Alright, after taking a look at the code...I think there are a few things we can do to help you.

 

From my guess, I would assume that you're probably way more comfortable in PHP than you are in javascript (most of the guys here are).  If this is your first real jump into asyncronous client side programming...I cannot stress this enough.

 

USE A JAVASCRIPT LIBRARY.

 

There are tons of them out there, but the one that I would reccommend most highly would be jQuery.  It takes the pain out of traversing and manipulating the DOM - and handles all the horrible cross browser quirks.

 

Another thing to keep in mind...everytime you change something in the DOM it's considered a somewhat process heavy execution.  In your current javascript, for every result that comes back you are inserting a new option value in your selectbox.  With 3 that isn't a problem, but if you have 100 you can find yourself running into some performance issues in a hurry.

 

Another thing to remember, with raw XMLHttpRequests is that IE will cache anything sent via $GET.  So in order for it to always force a refresh, you will need to append a dummy variable (usually time) to the end of your string.  Javascript libraries take that pain away too

 

It's much more friendly to compile all of your HTML - and do one insert instead.

 

Here is an example of how it would look in jQuery.

 

 

<?php
// All of your HTML head stuff would be above here, and also your javascript src file to include the jQuery library. 
?>

<script type="text/javascript">
// This function here is what executes after your page has loaded.  It then attaches an event listener to your select boxes (cleaner than putting them inline your HTML) and takes the ID value off of whatever select box has been modified.

$(function){
   $("select").bind("change",function(){

// The $(this) object is a jQuery object.  We want to pass the id and value that was selected from the select box
updateSelectBox($(this).attr('id'), $(this).val());
});
}

function updateSelectBox(id,value){
   $.post("/urlofthephpfile.php",
    {
       var1 : "whatever var",
       var2 : "another var"
    },
  // This function right here is what happens after the ajax request has completed.   In your PHP file you can go ahead and echo whatever option group you want, and then do one simple insert into your select box.
  function(data){
        switch(id){
          //  What we are doing here is looking at which select box was clicked, and then populating the correct select box based off that value.
          case 'selectbox_1':
                   $("#selectbox_2").html(data);
                    break;
          case 'selectbox_2':
              // This $("#selectbox) stuff that you see is the jQuery equivalent of getDocumentById.  The .html method just means it will replace anything that is inside of your select box with the return value from your php script.
                   $("#selectbox_3").html(data);
                   break;
    // this functionc an also handle the logic from your third select box, and populate another div underneath your select boxes with whatever the return result was.  This could be done in lieu of hitting a submit button...as soon as all parameters are selected it will goa head and execute your php script.         
       case 'selectbox_3':
           $("#results").html(data);
            break;
}
}

}
</script>

 

 

 

I don't know if I helped, or confused you with any of that.  :P  Basically raw javascript and ajax requests suck and while learning raw javascript is importnat - it's more of a pain in the ass than it's worth when great tools are available to help you.

 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.