eire web design home page contact eire-web design eire web design and development site map
stepping on in business
• Dependent Select Box using Ajax

Dependent Select Box using Ajax



One of the members on Irish WebMaster Forums asked for help in creating a simple dependent select menu and the most obvious option is by using Ajax, so I decided to put up this post with step-by-step instructions.

First, create a new PHP page (as we are going to use php for this) and name it “page1.php“.

On this page we are going to add the following javascript code, which will take care of our XMLHTTP request.

<script type="text/javascript" language="javascript">   

var ewd_domain = 'http://www.eire-webdesign.ie/'; //set domain   

var ewd_loading_img = ewd_domain + 'images/loading.gif';//set image path   

var ewd_loading_msg = 'Loading Data…';//set loading message   

var xmlhttp_obj = false;
//create the XMLHttpRequest
function ewd_xmlhttp(){   

 if (window.XMLHttpRequest){ // if Mozilla, Safari etc   

  xmlhttp_obj = new XMLHttpRequest();   

 }else if (window.ActiveXObject){ // if IE   

  try{   

   xmlhttp_obj = new ActiveXObject("Msxml2.XMLHTTP");   

  }catch (e){   

   try{   

    xmlhttp_obj = new ActiveXObject("Microsoft.XMLHTTP");   

   }catch (e){   

   }   

  }   

 }else{   

  xmlhttp_obj = false;   

 }   

 return xmlhttp_obj;   

}   //get content via GET   

function ewd_getcontent(url, containerid){   

 var xmlhttp_obj = ewd_xmlhttp();   

 document.getElementById(containerid).innerHTML = '<img src="' + ewd_loading_img + '" />' + ewd_loading_msg;   

 xmlhttp_obj.onreadystatechange=function(){   

         ewd_loadpage(xmlhttp_obj, containerid);   

         }   

 xmlhttp_obj.open('GET', url, true);   

 xmlhttp_obj.send(null);   

}        

function ewd_loadpage(xmlhttp_obj, containerid){   

 if ( xmlhttp_obj.readyState == 4 && xmlhttp_obj.status == 200 ){   

  document.getElementById(containerid).innerHTML = xmlhttp_obj.responseText;   

 }   

}      

Now will create a simple form with two select menus and a submit button:

<form name="select_m" id="select_m" action="<?php echo $_SERVER['REQUEST_URI']."?".$_SERVER['QUERY_STRING'];?>" method="get">      

<select name="sel1" id="sel1" onchange="ewd_getcontent('page2.php?sel1='+this.value, 'span1');">   

    <option value="">select...</option>   

    <option value="1">first</option>    <option value="2">second</option>   

    <option value="3">third</option>   

   </select>   

   <span id="span1">   

   <?php   

   include_once("_page2.php");    

   //this is the page that will create the second select menu   

   ?>      

   </span>   

   <input type="submit" name="submit" id="submit" value="Go..." />     

  </form>

Now save page1.php and create a new page “page2.php“, where we are going to create the second select menu which will change its options based on the GET request:

<?php   

$txt = "";   

$qs = $_GET['sel1'] != "" ? preg_replace("#[^0-9]#","",$_GET['sel1']) : "1";//I use preg_replace to sanitze the get request   

//which in this case must be numbers   

//this is manually created but it can be easily populated from a database   

if($qs != ""){   

 if($qs == "1"){   

  $txt .= "<select name='sel2' id='sel2' style='font-size:11px;'>   

     <option value=''>select...</option>   

     <option value='11'>first-first</option>   

     <option value='12'>first-second</option>   

     <option value='13'>first-third</option>   

    </select>";   

 }elseif($qs == "2"){   

  $txt .= "<select name='sel2' id='sel2' style='font-size:11px;'>   

     <option value=''>select...</option>   

     <option value='21'>second-first</option>   

     <option value='22'>second-second</option>   

     <option value='23'>second-third</option>   

    </select>";    

 }elseif($qs == "3"){   

  $txt .= "<select name='sel' id='sel2' style='font-size:11px;'>   

     <option value=''>select...</option>   

     <option value='31'>third-first</option>   

     <option value='32'>third-second</option>   

     <option value='33'>third-third</option>   

    </select>";    

 }   

 echo $txt;   

}   

?>

Save the second page, and using your preferred browser navigate to “page1.php”, make a selection and see how the second menu will change its values.

How it works? Simple.
We have the javascript code that will take care of our XMLHttpRequest.
As you have noticed we have added a span id html element that will hold our second select menu, which is passed to the Ajax code to replace its content with the html received from the “page2.php” using the innerHTML function:

............
document.getElementById(containerid).innerHTML = xmlhttp_obj.responseText;
............

We’ve added “onchange” function to the first select menu that will execute our javascript function, passing its value to the the second select menu for filtering the data, and also the span id to tell the function where the magic has to be executed.
Just in case javascript is disabled in the user browser, we’ve added a submit button as well so the form is still functional.

Few minutes of work and voila you’ve done it.
It wasn’t that hard was it?

You can see an working example here: Dependent select menus

Share and Enjoy:
  • Digg
  • del.icio.us
  • blogmarks
  • Reddit
  • StumbleUpon
  • Technorati
  • Blogosphere News
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • LinkedIn

Tags:

This entry was posted on Tuesday, November 13th, 2007 at 12:29 pm and is filed under Ajax. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 5.00 out of 5)
Loading ... Loading ...


  • 14 Responses to “Dependent Select Box using Ajax”

'Select Box' Selection Function - Page 2 - Irish SEO, Marketing & Webmaster Discussion Says:
November 13th, 2007 at 12:35 pm

[...] in case you don’t get the hang of it, I put up some step-by-step instructions and a sample page: Dependant Select Box using Ajax | Eire Web Design __________________ :. Used Car Sales :. Car Parts & Accessories :. Car Styling :. Auto [...]

'Select Box' Selection Function - Page 2 - Irish SEO, Marketing & Webmaster Discussion Says:
November 13th, 2007 at 3:15 pm

[...] louie Senior Member iTrader: (2) Recent Blog: Dependent Select Box using Ajax [...]

Joseph Grogan Says:
December 19th, 2007 at 3:51 pm

This is a very nice tutorial. Very easy to follow and everything…. Cheers

Louie @ Eire Web Design Says:
December 19th, 2007 at 4:04 pm

Glad you like it.
Ajax is not that hard to implement once you understand how it works, saying that so is everything else.

John Says:
December 23rd, 2007 at 8:20 am

Great little script, but it crashes Safari on Win!!

Louie @ Eire Web Design Says:
December 23rd, 2007 at 10:45 am

I have only tested the script using IE7, OPERA & FIREFOX.

Rapidz Says:
February 29th, 2008 at 7:05 pm

Took a bit of tweaking but got there in the end. Many thanks for the tutorial.

Louie @ Eire Web Design Says:
February 29th, 2008 at 8:00 pm

You should’ve ask for help if needed. Great help can be also found at http://www.irishwebmasterforum.com/

VISHAL Says:
April 21st, 2008 at 10:37 am

YOUR CODE IS VERY HELPFUL TO ME
THANKYOU VERY MUCH….

Arun Says:
December 12th, 2008 at 6:44 am

i have php and 3 to 4 ajax in the same form and would like to send all the from Php and ajax into one row in the database. Can somebosy help with Code

mark c Says:
January 1st, 2009 at 7:26 pm

thanks muchly! worked a treat for generating three levels of dependent dropdowns fed from mysql db – I owe you a pint of the black stuff
- note to others : change the html & entitities to ordinary ampersands in the last function of the javascript (well I had to anyway)

Louie @ Eire Web Design Says:
January 1st, 2009 at 7:59 pm

No problem Mark and yes indeed, if you copy and paste from this page you have to do that and also the double-quote marks but if you go to this sample

http://www.eire-webdesign.ie/sample_dependant_select_menu.php

and copy from the source you don’t need to.

Cle Silva Says:
June 19th, 2009 at 7:52 pm

I have to say, this is simply awesome! I’ve been searching for ages for a cascading dropdown example that would work, and I was nearly giving up until I found this one. Works beautifully with mySQL too, with a few changes! Thanks very much for sharing, man!

AJAX Query Says:
June 16th, 2010 at 1:39 pm

[...] onclick="getcontent('page.php', 'cpost');"/> I'm using louie's code(Dependent Select Box using Ajax | Website Design Ireland, Website Development) as a guide! Any ideas? ign.ie | war.ie Reply With Quote [...]

  • Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Links...

Chicklets...
  • http://www.eire-webdesign.ie/blog/feed/
    http://www.eire-webdesign.ie/blog/feed/
    Google Reader or Homepage
    Add to My Yahoo!
    Subscribe with Bloglines
    Subscribe in NewsGator Online
    add to msn
    Add to My AOL
    Add to Technorati Favorites!
    pageflakes
    windows live