Populate triple drop down list from database using Ajax and PHP

Advertisement

I’ve got many email from people asking for populating triple drop down list from the database without refreshing page using Ajax and PHP after posting the first article related to the ajax dropdown list using php .In this post, I’ve put three drop down of country , state and city and the drop down’s value changes without refreshing the page. Now let show you how to create it quickly.
First create the following tables of country city and states,

CREATE TABLE `country` (
  `id` tinyint(4) NOT NULL auto_increment,
  `country` varchar(20) NOT NULL default '',
PRIMARY KEY  (`id`)
) TYPE=MyISAM   ;

CREATE TABLE `state` (
 `id` tinyint(4) NOT NULL auto_increment,
 `countryid` tinyint(4) NOT NULL,
`statename` varchar(40) NOT NULL,
PRIMARY KEY  (`id`)
) TYPE=MyISAM   ;

CREATE TABLE `city` (
`id` tinyint(4) NOT NULL auto_increment,
`city` varchar(50) default NULL,
`stateid` tinyint(4) default NULL,
`countryid` tinyint(4) NOT NULL,
PRIMARY KEY  (`id`)
) TYPE=MyISAM   ;

Now place the following form in the index.php file

<form method="post" name="form1">
 <table border="0" cellpadding="0" cellspacing="0" width="60%"><tbody>
  <tr>
   <td width="150">Country</td>
   <td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option>       </select></td>
  </tr>
 <tr>
  <td>State</td>
  <td>
  <p id="statediv">
  <select style="background-color: #ffffa0" name="state"><option>Select Country First</option>       </select></td>
</tr>
<tr>
  <td>City</td>
  <td>
  <p id="citydiv">
  <select style="background-color: #ffffa0" name="city"><option>Select State First</option>       </select></td>
</tr>
</tbody></table>
</form>

As you can see above, in the onChage event of the country drop down getState() function of the javascript is called which change the options values the State drop down, let’s look at the code the getState() function.

function getState(countryId)
{
   var strURL="findState.php?country="+countryId;
   var req = getXMLHTTP();
   if (req)
   {
     req.onreadystatechange = function()
     {
      if (req.readyState == 4)
      {
	 // only if "OK"
	 if (req.status == 200)
         {
	    document.getElementById('statediv').innerHTML=req.responseText;
	 } else {
   	   alert("There was a problem while using XMLHTTP:\n" + req.statusText);
	 }
       }
      }
   req.open("GET", strURL, true);
   req.send(null);
   }
}

The code of the PHP file findState.php, which populate the options in the drop down of the state which is fetched from Ajax , is given below

<? $country=intval($_GET['country']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,statename FROM state WHERE countryid='$country'";
$result=mysql_query($query);

?>
<select name="state" onchange="getCity(<?=$country?>,this.value)">
 <option>Select State</option>
  <? while($row=mysql_fetch_array($result)) { ?>
    <option value=<?=$row['id']?>><?=$row['statename']?></option>
  <? } ?>
</select>

In the above state dropdown, getCity() function is called in onChage event with countryId and stateId parameter, now let’s look at the code of the getCity() function

function getCity(countryId,stateId)
{
  var strURL="findCity.php?country="+countryId+"&state="+stateId;
  var req = getXMLHTTP();
  if (req)
  {
    req.onreadystatechange = function()
    {
      if (req.readyState == 4) // only if "OK"
      {
        if (req.status == 200)
        {
          document.getElementById('citydiv').innerHTML=req.responseText;
        } else {
          alert("There was a problem while using XMLHTTP:\n" + req.statusText);
        }
      }
    }
    req.open("GET", strURL, true);
    req.send(null);
  }
}

In the above ajax function, findcity.php is called and this PHP file populate the city dropdown according to the supplied parameters country and state from get method. Now let’s look at the code of findcity.php,

<?php $countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,city FROM city WHERE countryid='$countryId' AND stateid='$stateId'";
$result=mysql_query($query);

?>
<select name="city">
 <option>Select City</option>
  <?php while($row=mysql_fetch_array($result)) { ?>
 <option value><?=$row['city']?></option>
<?php } ?>
</select>

And thats all, the triple drop down list of city, country and state using Ajax and PHP will be populated.
VIew Live Demo
To download full source code, click here

Popularity: 32% [?]

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

Related Posts

» Changing textbox value from dropdown list using Ajax and PHP
» Change dropdown list (options) values from database with ajax and php
» SQL Injection Attack – Examples and Preventions in PHP
» Slider Using PHP, Ajax And Javascript

157 Comments on “Populate triple drop down list from database using Ajax and PHP”

  • Babak wrote on 24 January, 2008, 21:57

    I really love and enjoy your blog, Thanks.

  • Roshan wrote on 28 January, 2008, 6:26

    Thanks a lott babak….

  • Newbie wrote on 21 February, 2008, 10:52

    Nice job. Thanks!

  • Fajar wrote on 29 March, 2008, 2:18

    After almost 2 months searching and learning AJAX from the bottom for my job problem, I found your site, I think this is my search end. Thanks Roshan, now I have learning new knowledge and have idea how to fix my previous AJAX code. Thank you so much for your code share. :-)

  • Roshan wrote on 29 March, 2008, 6:25

    Thanks Fajar…thanks a lottt…and please let me know some negative aspects of this blog as well..which will help me to improve the quality of this blog…

  • Sean wrote on 31 March, 2008, 4:17

    great blog with a TON of information.
    looking for a suggestion on how to clear the 2nd and 3rd lists if the first is changed to prevent the possibility of submitting the wrong data.

    thanks again

    Sean

  • Roshan wrote on 31 March, 2008, 5:08

    on that situation you can write conditions in fincity.php and findstate.php to clear the dropdown ..
    hope this helps

  • Sean wrote on 1 April, 2008, 5:01

    makes sense, i was thinking that when the month changes the state drop down it would change the city drop down, and it doesn’t
    i guess need to learn more about java script

  • Kim Hauw wrote on 9 April, 2008, 9:48

    Thanks u very much :)

  • swathi wrote on 10 April, 2008, 13:39

    I have done some modifications in database content and in php pages..
    and i have run the same…its not working….
    pls go thru my code…

    function GetXmlHttpObject()
    {
    var xmlHttp=null;
    try
    {
    xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
    try{
    xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
    }
    catch(e)
    {
    xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
    }
    }

    return xmlHttp;
    }
    var xmlHttp;
    function getstate(countryid)
    {
    xmlHttp=GetXmlHttpObject();

    if(xmlHttp==null)
    {
    alert(“Browser Does not support HTTP request”)
    return;
    }
    var url=”findstate.php?country=”+countryid;
    xmlHttp.onreadystatechange=statechanged;
    //alert(url);
    xmlHttp.open(“GET”,url,true);

    xmlHttp.send(null);
    //alert(url);
    }
    function statechanged()
    { // alert(‘url’);
    if(xmlHttp.readyState==4 || xmlHttp.readyState==”complete”)
    {
    document.getElementById(‘statediv’).innerHTML=xmlHttp.responseText;

    }
    else
    alert(‘wait’+xmlHttp.readyState);
    }

    function getcity(countryid,stateid)
    {
    xmlHttp=GetXmlHttpObject()
    if(xmlHttp==null)
    {
    alert(“Browser Does not support HTTP request”)
    return;
    }
    var url=”findcity.php?country=”+countryid+”&state=”+stateid;
    xmlHttp.onreadystatechange=statechanged2;
    xmlHttp.open(“GET”,url,true)
    xmlHttp.send(null)

    }
    function statechanged2()
    {
    if(xmlHttp.readyState==4 || xmlHttp.readyState==”complete”)
    {
    document.getElementByID(‘citydiv’).innerHTML=xmlHttp.responseText
    }
    }

    Country
    Select Country
    India
    USA
    Canada
    Stateselectstate
    Cityselectcity

    and my findstate.php code is like this
    <?php
    $countryid=$_GET["country"];
    $con = mysql_connect(“localhost”,”root”,”root123″);
    if(!$con)
    {
    die(“could not connect:”.mysql_error());
    }
    mysql_select_db(“testtool”,$con);

    $query=”select id,statename from state where countryid=’”.$countryid.”‘;
    $result=mysql_query($query) or die(mysql_error());

    echo “<select name=’state’ onchange=’getcity(“.$countryid.”,this.value)”;
    echo “”.count($result).”";
    while($row=mysql_fetch_array($result))
    {
    “.$row['statename'].”
    }
    echo “;
    mysql_close($con);
    ?>

    After selecting country..it is displaying select option for state….
    pls guide me….

  • Roshan wrote on 11 April, 2008, 14:29

    well…after selecting country, it does display the dropdown for stat, I couldn’t get what is your problem !!

  • Sachin wrote on 22 April, 2008, 9:27

    Thanks Roshan.
    I love and enjoy your blog.
    tell me some negative aspects of this blog as well,to improve myself.
    Thanks u very much once again.

  • mario wrote on 30 April, 2008, 15:37

    thx roshan!
    just what i was looking for…
    i have to link this with editable grid what will easy my life a lot!
    thx again… :-) )

  • mario wrote on 30 April, 2008, 15:46

    btw…
    i took a close look and noticed that i have no idea how can i make that after user makes his choice to, for example, open a page linked to what he choose?

    nevertheless, this is still a good thing…

  • Roshan wrote on 30 April, 2008, 16:31

    well mario….you can use window.open to open a new link using javascript

  • mario wrote on 30 April, 2008, 16:50

    thx!
    ill see what i can do…
    im novice, so maybe a few line of code..(on your example)
    City div is generated by php, and i really dont know where should i put it… :-)
    bye!

  • Roshan wrote on 30 April, 2008, 17:57

    ok tell me in detail how do you want it to happen in detail so that I can tell you in detail…

  • mario wrote on 30 April, 2008, 20:46

    ok thx!
    i will use framesets so that combo boxes will remain visible…
    in other words im planning to retain this kind of functionality as it seen on this site:
    http://www.yxscripts.com/cs/examples/loader3.html

    so basically when user chooses city (third combo option) script should automatically load some page in lower(down one) frame…
    as list of the cities are automatically populated im wonder if that is even possible to do in this way…?

    list is populated by admin directly to the database and then (data are) used on few pages of the same domain..

    thx…

  • mario wrote on 30 April, 2008, 20:50

    and yes, this is tested web site…
    it has a lot of things to do still..

  • mario wrote on 30 April, 2008, 21:30

    just to tell you that i found one php grid (php buider) that satisfied things that i needed..

    thx anyway…
    cheers!

  • Roshan wrote on 1 May, 2008, 4:11

    nice to hear that mario..

  • mario wrote on 1 May, 2008, 14:43

    yes, thank you!
    nice thing though!
    cheers! :-)

  • Doug wrote on 16 May, 2008, 17:59

    on that situation you can write conditions in fincity.php and findstate.php to clear the dropdown ..
    hope this helps

    Thanks for sharing this.

    Would you provide some code snipits or give some suggestions as to th functions I should use to write the conditions.

  • Prince wrote on 19 May, 2008, 9:21

    Hello Roshan. I am using same downloaded files (without change). After selecting country it shows empty city list in drop down. It does not get City Names. Why ?

  • Leah wrote on 25 June, 2008, 6:37

    Thank you very much for the tutorial. I am trying to create 4 drop down lists so i am modifying your code to include another list, but i am having problems.

    This code populates the first two drop downs but when i try to populate the third drop down it is not make a call to the script. Im not sure why. In your code you have the onchange call in your php script so i thought that since this is a server side script the onchange needed to be in the html, but that doesnt seem to work. Do you have any ideas?

    Thank you for all your help.

  • xerxes wrote on 27 June, 2008, 3:58

    Hi, I’ve had problems loading the page. I can’t load the codes with just 2 dropdown boxes by Roshan as well. The database is connected. After selecting the country, the next dropdown box does not load. I’m stucked.

  • x wrote on 2 July, 2008, 3:30

    gosh why doesn’t roshan or anyone reply anymore?

  • Roshan wrote on 2 July, 2008, 4:49

    Can you first check the the response in ajax by using alert(req.responseText); and you can see what is the response coming from that file

  • xerxes wrote on 2 July, 2008, 7:04

    <select name=”state” onchange=”getCity(,this.value)”>

    Hi i got this error message when i used firebug. Am clueless. It looks fine. Are you able to help?

  • xerxes wrote on 2 July, 2008, 7:15

    does the demo codes have bugs? Because i am trying to debug the demo codes all these while.

  • Roshan wrote on 2 July, 2008, 8:57

    I think there is one “,” extra in the onchange=”getCity(,this.value)” just remove , before this.value

  • Sonny wrote on 2 July, 2008, 14:39

    It won’t let me post my comment.

  • Roshan wrote on 2 July, 2008, 15:47

    @Sonny – LOL .. then how were u able to post that comment??

  • Sonny wrote on 2 July, 2008, 17:31

    Sorry, that was my second comment. Turns out my first comment was too long.

    I ended up figuring it out. I had put a piece of code for you to look at with me. But like I said… I figured it out.
    I will say that I just found your blog yesterday and spent about 3 hours on your site reading over all the different PHP/AJAX topics.
    I love it.
    It is one of the best learning resources I’ve seen for people who are new to AJAX but need to implement it now.
    Thanks, keep up the good work.

    Sonny.

  • Roshan wrote on 2 July, 2008, 18:03

    @sonny – Thanks a lot for the appreciation. If you liked this blog so much then why don’t you subscribe for the RSS feed of this blog by email..

    http://www.feedburner.com/fb/a/emailverifySubmit?feedId=1456759&loc=en_US

    and help me to become the blogging idol.. :-)

  • Tony wrote on 9 July, 2008, 16:19

    Love the auto-populate scripts. One question, how can you post a url based upon the final result “City”.

    For example, once you get to the final combobox and choose “Los Angeles” is there a way to redirect to a specific url, based upon final selection. Sorry if this sounds confusing.

    Thanks in advance

  • Roshan wrote on 9 July, 2008, 17:23

    you can use the javascript code document.location=’abc.php’; on the onchange event of that particular dropdown…

  • Sanjeev wrote on 16 July, 2008, 8:10

    I am listing County once the state is picked and it works like a charm but when I click on City- I get this message. There was a problem while using XMLHTTP:Not Found.

    Web site is a work in progress. Please help.

    Thanks

  • Roshan wrote on 16 July, 2008, 9:49

    It is saying not found means…it not finding the the PHP file..can you check the location of the file and how you’re accessing it via javaScript

  • Sanjeev wrote on 17 July, 2008, 0:19

    Found the mistake. Upper case and lower case issue – I was calling findCity.php but script was named findcity.php

    Thank you for leading me in the right direction.

  • John wrote on 18 July, 2008, 18:10

    There is a problem with either the GetCity function or the findState.php. The problem is from this line
    <select name=”state” onchange=”getCity(, this.value)”>

    this.value is not being passed. The $country variable is. This is why so many people are having difficulty displaying the city. I am not sure why it is not being passing. The sample website works, so can you ensure that the findState.php on there is the same as you have listed?

    Thank you in advance for your help.

  • Roshan wrote on 19 July, 2008, 4:53

    @john – I think everything is right there with the code and only few people are having difficulty in using them due to some problem

    Anyway, I’ll check the code again and see if something is wrong there or not

  • Bobik wrote on 24 July, 2008, 6:15

    I had no problem testing the script (IE, Opera, FW) in a Windows XP PC with Apache, PHP, and Mysql installed manually. However, in another Windows PC where mysql is installed as a service, Apache and PHP installed manually, the second dropdown (State) will disappear after selecting an option from the country dropdown. It is only an observation. I hope some readers will find it useful.

  • Vec wrote on 30 July, 2008, 13:00

    Nice code, but it doesn’t seem to work for me. Nothing happens for me when I click on a value in the first list. I know all my stuff is set up correctly because using a different ajax script it works fine. I’m more then sure all of my variations of your code are correct, and I know the findstate.php works because if I type in findstate.php?country=2 or w/e It works fine. However there seems to be something wrong with it doing an auto refresh when you change the value.

  • Vec wrote on 30 July, 2008, 13:17

    Hmm, I seemed to have gotten it, your code in your zip file contains many illegal characters, using different ” errors out, and also your xml object is named differently, if you fixed that your code would be splendid :)

  • Roshan wrote on 30 July, 2008, 17:08

    @Vec – Ya I see this I’ll surely going to make the correction..

  • Ramsey Smith wrote on 3 August, 2008, 21:32

    Hi,
    Everything works fine in FIrefox nut in IE I am experiencing error ‘Object Not found”

  • Roshan wrote on 4 August, 2008, 17:52

    @Ramsey and @Vec – I’ve updated the code and mistake. You can download the source code now and it will work in IE properly as well you’ll not find “Object not found error”

  • prakash wrote on 5 August, 2008, 5:01

    i have problem in Ajax code. The error is encounter as
    “There was a problem while using XMLHTTP:not found ”
    plz tell me how to resolve it.

  • Roshan wrote on 5 August, 2008, 5:31

    property look at the path of the file …as it is giving 404 not found error. You can check the path as well as character case of PHP file

  • Ramsey Smith wrote on 5 August, 2008, 6:28

    Roshan,

    I tried new version and it works very well. What can I say rather that you’re a star. Thanks a lot.

  • imran wrote on 6 August, 2008, 12:18

    triple drop down list from database using Ajax and PHP

    this code is not running?

  • Bardiy wrote on 21 August, 2008, 17:14

    Hi, Thank yooooooooooooooooooooou for this code, this work greatly. best wishes

  • kero wrote on 24 August, 2008, 6:58

    Thank you for the script. am a beginner so your script was very helpful. But I am having trouble passing the variables upon submit. Please help.

  • Roshan wrote on 24 August, 2008, 8:58

    What kind of problem you’re facing can you please explain it ?

  • kero wrote on 25 August, 2008, 0:40

    oic, let’s try one more time. so sorry for the ultra long post

    text field:

    bracket input type=text name=’score[score]‘ value=” bracket

    submit button:
    bracketinput type=’hidden’ name=’action’ value=’submitscores’ bracket
    bracket input type=’submit’ class=’button’ name=’submit’ value=’Submit >>’ bracket

  • dolly wrote on 26 August, 2008, 7:03

    To the brainee himself,
    Thanks a lot Roshan,was looking exactly for the same thing,you made my life easier.
    Bye
    Regards,
    dolly

  • Damo wrote on 28 September, 2008, 8:41

    Hi Roshan

    Love your work.

    However, when I change the option value of USA to be “USA” and echo $country in findState.php I receive the value 0. It doesn’t seem to like text?

  • Damo wrote on 28 September, 2008, 11:13

    Got it

  • Roshan wrote on 28 September, 2008, 15:42

    @Damo – what was the problem and how did you solve it can you share it with us ?

  • Damo wrote on 30 September, 2008, 11:55

    The solution was simple. The first line in the php file has an intval function. This just needed to be removed.

    However, I have been playing with your code and think I have found an issue. When the db contains a value with a space, only the data before the space is returned.

  • Roshan wrote on 1 October, 2008, 5:13

    @Damo – intval() is there for preventing sql inject attack, do filter user input before using it with database.

  • Lessy wrote on 4 October, 2008, 17:01

    Hi Roshan,

    I just wanted to say thanks for sharing this script with us. I used it on my website to let the user select a category and then a genre thats in that category :)

    There is only 1 thing i can’t seem to “adjust”, because when i do so the page where the genres will be loaded, does not load.

    When i change:
    req.onreadystatechange = function() {
    if (req.readyState == 4) {
    indto:
    req.onreadygenrechange = function() {
    if (req.readyGenre == 4) {

    it doesnt work anymore. I also dont understand what that part axactly does, buy i am a real javascript n00bie ;)

    Greetz, Lessy

  • Jim wrote on 6 October, 2008, 3:41

    Hi, Roshan

    I am new to web programming, and really like the details you posted. However, I’m stuck when I try to populate ‘state’. I downloaded your source files and always encountered a blank ‘state’ > after selecting ‘country’. Thanks for some guidance.

  • billy wrote on 16 October, 2008, 16:40

    Hello,

    I am trying to use your code but I am having problems with the last list box. Instead of calling the city function I put onchange=”alert(‘hi’);” Nothing happens at all when I select something. The first part of the code works so I am stumped.

  • karthick wrote on 2 November, 2008, 12:08

    This is my problem..

    I tryed to use this ajax example into a project..
    but while doing this task it shows an error “There was a problem while using XMLHTTP:Not Found”

    Now i want to know how to debug this problem…
    Can u help me?

  • Shubhkriti wrote on 11 November, 2008, 17:54

    Hey it is not working for me?

    Kindly visit this page and see http://www.shubhkriti.net/en/post.php

  • jhd wrote on 13 November, 2008, 21:49

    if i want to add the 4th and 5th dependent drop down. what will you suggest to do.
    Thank you

  • venki wrote on 2 December, 2008, 10:12

    Hi,

    I sent u number of comments but i didn’t received any reply or solution… this is final one…. actually i used the above code to populate the drop down list boxes it is working fine… but my problem is when i used to this code and submit the form the first drop down list box value only stored in my database…. second one is stored as empty… am using only two… plz help me…..

    advance thanks….

  • jhd wrote on 3 December, 2008, 19:54

    i am trying to add the 4th and 5th they depend on 1+2+3rd query please help

  • John wrote on 7 December, 2008, 17:32

    anyone here monitoring this forum because there is bunch question not answered:

    like

    i am trying to add the 4th and 5th they depend on 1+2+3rd query please help

  • Pradeep wrote on 8 December, 2008, 9:52

    Hi Roshan

    The first and the second drop downlist works absolutely fine but on changing the 2nd drop down items nothing happens for the 3rd drop down.
    basically the javascript “getcity” function is not able to execute while we select an item from the STATE.

    I need this urgently.. any help would be greatly appreciated.

    thanks!!

  • Pradeep wrote on 8 December, 2008, 10:34

    Hello Guys
    I found out the issue. In the findState.php file you need to make sure that the arguments are properly passed
    <select name=”state” onchange=”getCity(”,this.value)”>
    should be in ” single quotes if its a string.
    This worked for me
    thanks Roshan for the code !!

  • Abs wrote on 11 December, 2008, 23:27

    Hello,

    When I pass a countryid which DOES not have a state assigned to it in my database, I get a dialog which says “There was a problem using XMLHTTP. Not found”. Is there a way to suppress this error message the “state select” list is just empty ?

    Thanks Abs

  • Shubhkriti wrote on 17 December, 2008, 13:15

    It worked for me. I think there must have been some browser problem. It is working fine for me. Visit my site at http://www.shubhkriti.net

  • Raja M wrote on 19 December, 2008, 4:42

    Hi Roshan!!!!
    I got your Triple combo ajax code. It’s working nice. thanks for your code

    By
    Raja M

  • Rahul wrote on 26 December, 2008, 12:40

    thanks buddy ….i’ve implemented 4th , 5th and 6th combo boxes.. you code is easy to understand.thanks for the demo.

  • Michael wrote on 28 December, 2008, 23:22

    Thanks for the code!!! It works great. Question? Once all the fields are selected (country, state, and city) how can you submit (button) the information to a detail page based on the city ID?

    I did read a post that referred to “you can use the javascript code document.location=’abc.php’; on the onchange event of that particular dropdown…” Is that to call just a URL, and can I add to it to provide page results based on any particular ‘ID’?

    Your help is appreciated.

    Thanks Again!!!

  • Michael wrote on 3 January, 2009, 0:24

    OH YES!!! I figured it out. Thanks for not responding, because it made me more persistant.

    Thanks again!!!

  • sieza wrote on 5 January, 2009, 4:53

    hello..
    Im facing the problem of my final year project. I dont know what to do until i found this blog. thanks alot to the owner! appreciate it so much. tq

  • Vidya Kiran wrote on 9 January, 2009, 12:01

    Dear Mr.Roshan,

    The code is very helpfull for me but i need a small change when i select country it is showing states and when i select states showing cities but when i change country again the cities list should not show previous cities it should ask the user to select state first. can u please change the code to work like that.

    Thanks in advance.
    Vidya Kiran.T
    Vijayawada
    Andhra Pradesh

  • Vidya Kiran wrote on 9 January, 2009, 12:24

    Dear Mr.Roshan,

    I have another question, by using this way i ab able to select country, state and city and store this along with some other data into database, when it comes to edit mode of a data how can i show it as selected country,state and city. please help me in this issue.

    Thanks in advance.
    Vidya Kiran.

  • James wrote on 12 January, 2009, 17:15

    Hi Roshan,

    I have a question, actually two.

    (1) I am using the country name as the actual string (instead of countrycode as integer value). This is because of requirement. I would like to know how to handle a string with a space (like “United States”). this.value is picking up only the first word “United” to hand over to javascript during the uri query string formation. How can I overcome this to include the space and any following words as well ?

    (2) So as based on my requirement if I am not using countrycode as integer value but as string/character data, what other php / filter check can I use to protect fro sql injection attack that may be applicable to string type data.

    any ideas with how to implement with a code example for both (1) and (2) would be great.

    Thanks for this wonderful tutorial. It is the best example I have found so far on the web and it works great except the issues I mentioned based on my requirements.
    -james.

  • shree wrote on 14 January, 2009, 7:23

    Hi Buddy
    I am using the script but its not working in IE , when i try to get the values by $_Post method it returns blank !
    its working fine in Mozila firefox
    Any Solution?
    Thankx in advance

  • Steve wrote on 24 February, 2009, 6:08

    Roshan,

    Thank you for providing the script. I really appreciate it.

    Would you be so king as to provide the addtional script need to insert the selected text values into a table? I can insert the selected value into my table, but this is the integer associated with the user’s choice. How do you insert all three text values into three distinct columns in a table? i.e. Canada, British Columbia, Vancouver. not 2 , 2, 4.

    Thank you very much for your help.

    Steve

  • vinod wrote on 7 March, 2009, 10:31

    Thanku very much

  • sreenu wrote on 26 March, 2009, 14:40

    it is very nice example. but i am facing one problem that is after posting the values i want to get the
    posted value as selected and remaing values in the drop down could you please pls help me….

    thanks,
    Sreenu

  • Harshal wrote on 6 May, 2009, 7:55

    Hi ,Thanx for ur excellent support.

  • steve wrote on 9 May, 2009, 3:32

    can you tell me how i can add multiple sets on the same page? i need for start and finish locations.

  • aminay wrote on 12 May, 2009, 8:34

    Hi,
    I would this code but with oracle database ,I make some modification to connect with oracle bu not work,
    please give me the full solution,
    thanks roshan!

  • Andrew wrote on 3 June, 2009, 9:35

    Hi I am using your triple drop down menu, but I would like to place more sets of 3 drop down menus on the same page. The problem I am facing is how to make them indipdendent from one another. If I just duplicate the drop down menus, then when I make a selection in the second set of menus the values from the first changes.
    How can I solve this? I believe it has to do with the ajax script that should “know” I need to handle more than one set of 3 drop down menus, but I am not familiar with ajax…
    can you please help me?
    thank you

  • Sove wrote on 22 June, 2009, 22:44

    The script is working successfully, thank you. But how can we combine this script with “Changing textbox value from dropdown list using Ajax and PHP” script. For example when I changed the first drop-down box, I want that second drop-down box is going to be changed and on another tag, the value of textbox is going to be changed.

  • Ivo75 wrote on 28 June, 2009, 12:21

    Hi Roshan this is very good and work fine in Mozilla but have some litle mistake in IE7 when I insert new record in database this record isn’t view in IE7 but in Mozilla record is view. If You want I can post my code

  • Daniel Burke wrote on 1 July, 2009, 19:25

    hello, thank you for your post. I wonder if you can help me with something. I’m using a similar function that I wrote to generate a list based on the previous selection just like yours, and just like yours it seems the AJAX function is echoing the code to the document in, kind of, a virtual way. When I view the source on my page, the code that is echoed back via AJAX does not display. The same happens with your code as well. This becomes a problem because I want to send the variables( the names of the options) to another php file to be inserted into a database or emailed. Since they aren’t really there…the values are never filled and the PHP script returns and error.

    Is there any way to do this?

  • Dave wrote on 22 July, 2009, 8:39

    Hi everyone. Great code and thanks alot, just what I need. I have modified it for a similar project i’m working on and it works fine until the third doprdown. Although the funtion is called and php script activated, the second variable (state in your case) is not recognised, so the dropdown remains empty. If I specify a value in the query instead its fine. The problem is passing the variable between the scripts. i don’t know why it doesn’t work for me, any light on how these variables are passed would be great. Thanks alot again great blog.

  • Joseph wrote on 30 July, 2009, 15:29

    @ Dave, did you find a solution to your problem yet as I’m facing the same issue.

  • Picas wrote on 31 July, 2009, 7:15

    Thanks so much.. After long time i got your great tutorial.

  • kenan wrote on 15 August, 2009, 10:33

    Can someone convert this code into asp and java please?

  • Picas wrote on 18 August, 2009, 14:46

    Hi Roshan..

    something cause my project need the 4th combobox that still have relation with 1st, 2nd and 3rd combobox..

    how can we simply customize your triple populate combobox..??

  • cva wrote on 19 August, 2009, 14:05

    Hi Roshan,

    Thanks a lot for u r script.
    Its worked for me like a charm…..

  • Picas wrote on 23 August, 2009, 6:34

    Any Help for 4 populate combobox…?
    Please Help..

  • Naveed wrote on 1 September, 2009, 21:35

    Hi Roshan:

    Thanks for this wonderful tutorial+script. I am a novice to PHP but well experienced with HTML. Is it possible to open up a new web page upon clicking the “Submit” button? If so, does that web page need to be created manually in HTML or could that be created dynamically based on what selections users have made. For example, if users have selected, US –> New York –> Buffalo then the page should only show the information specific to Buffalo, New York. Can an admin interface be applied to this script so that adding/deleting countries, states, and cities be made easier?

  • maleli wrote on 3 September, 2009, 20:36

    Hi and thanks for this great script. It worked great for me.
    I only have one little issue. My application is entirely in spanish and some words have accents on them. When I retrieve them I get a question mark. I tried getting results directly from getCity.php for example, and it displays correctly. Only when it’s displayed through the AJAX request I get this error.
    Is there any way to fix this?

  • meir wrote on 7 September, 2009, 8:59

    HI

    Your code is very usefull exactly what I need for an upcoming project. My question is that since the form is posting to itself how can I transfer the final selected data to another form?

    In the past I used the following

    if ($_POST['Submit']==’Login’)
    {

    But its not working

  • roman weaver wrote on 8 September, 2009, 19:46

    No matter what i try i cannot get it to work on IE7 or IE8

    i have amended the code somewhat but it works on ALL other browsers but those two.. what can i do???
    help!!!!!!!!!

  • Shannon wrote on 16 September, 2009, 17:58

    Hello Roshan,

    I have utilized this script to only use the country and state part. It seems to be working great. My problem that I am having is that the Country and State ids that are selected are not going into the DB correctly.

    For example, If I choose United Kingdom for the country which has an ID of 190 (you can view source to see that the value of this option is 190) and then select Scotland as the state which has an ID of 3007, it inserts 127 for both country and state IDs in the table of my DB.

    I don’t know why this could be? Have you heard of this before?

    One more question too. What does “if (req,readyState == 4)” and “if (reg.status == 200)” mean in the javascript?

    Thanks for all you have done with this code the selections work great. Just need to find out the id issues.

    Shannon

  • Shannon wrote on 16 September, 2009, 18:37

    Hey Roshan,

    I found the problem. It was a DB field type mistake.

    Thanks anyway! Great Script once again.

    Shannon

  • jco wrote on 25 September, 2009, 21:45

    Great code!

    Quick question. I’ve got it set up in an project I’m working on but I ran into a problem. Is there a way to pass alpha stings? I.E. if the values on the first drop down were alpha instead of numeric. I had been trying to pass alpha strings, but it only passes “0″. I looked back at your code and noticed that you always used numeric values so I tested my code with a numeric value and it passed it just fine. I hope that made sense.

    Is there a way to pass an alpha string?

    Thanks for the help!

  • jco wrote on 25 September, 2009, 22:10

    moments later, problem solved.

    didn’t think about the intval bit of php code. Changed to strval and all is well.

  • kwame wrote on 26 September, 2009, 7:59

    Is there a way we can get this to work with more than just three select, perhaps increase it unlimited

  • vishnu wrote on 30 September, 2009, 10:10

    very bad very bad its not working for me

  • Noel Pulis wrote on 5 October, 2009, 20:53

    First of all thanks a lot for the code, it works like a charm.

    I have a question thou. When I submit to another page from the form… the state of the country dialog box is not retained. The value is not passed.

    Any help would be greatly appreciated. Thanks.

  • Noel Pulis wrote on 5 October, 2009, 20:59

    Sorry to disturb again. My issue is exactly as follows.

    Since when the submit button is clicked. The changes and contents of the state dialog box are not retained… and if there is an error, the user will be forced to re-select the country again.

    Is there anything I could do about it please?

  • mariane wrote on 16 October, 2009, 3:43

    Hi, nice tutorial… can i ask what if i like to add another dropdown after city like schools… do i need to modify the function getXMLHTTP() {}?

  • shambhu sharan wrote on 17 October, 2009, 10:11

    nyc blog to help new and novie web developers…thanks

  • Haroon wrote on 17 October, 2009, 17:18

    Hey, thanks for the code.

    I currently need help understanding the last part of findstate.php.

    I notice you put a new dropdown menu for the state yet in index.php their is already a drop down for state.

    but in findstate.php you added on the onchange javascript function.
    When I tried the code it shows the states dropdown within the states dropdown. So their is 2 state drop downs but one is inside the other.

    When I take out the tags and Select A State I would get a working state drop down showing the states being populated from the database.

    The problem is that I can’t populate the third drop down menu. Since I didn’t use the onchange.

    Can you explain the last part of the findstate.php where you populate the drop down menu.
    I want to know why you added the select tags? Also explain how it works .like in your index.php you already created the state drop down menu. It looks to me you create 2 state drop downs.

    I am not clear on this part. So if you can explain how we can put a onchange on the states drop down menu. That would be great.

    Thank you for your time.

  • Haroon wrote on 31 October, 2009, 2:43

    Hi, I now can’t pass the values. I am trying to pass them with post from form to another php page.

    I am not getting the values on the other page. So the form becomes useless. How do I fix this?

    how does the values stay put.

  • Azawe wrote on 11 November, 2009, 11:10

    Thank you man for the script But i wana know how to change encoding coz the alphabet look like this ?????

  • phyu aung wrote on 13 November, 2009, 5:09

    i test this but i cannot reach findState.php

  • Melinda wrote on 18 November, 2009, 0:12

    Hi, I just started using PHP last week and this week I’m attempting to create an advanced search form. I want them to link together like the state/city/zip example and had the hardest time finding a good example online of how to handle the situation once there are more than two selection boxes available. Your post has been great!

    I’m having an issue with my second selection box. If I select something in my first box it filters the second box correctly. If I select something in my second box I’m getting an error somewhere but I’m not sure how to debug it. If I change the code of my second box so that it works like the first (ie it doesn’t pass along the data from the first box as a second parameter) everything works fine so I know I don’t have an obvious typo somewhere.

    My second selection box looks like this:
    <select multiple size=5 name="Package" style="width: 15em;" onchange="setPackage(, this.value)”>
    …………..

    I think the issue is with the “”. All of the other opening brackets I have in my code are “<?php" but if I try doing "<?php=" Eclipse gives me an error.

    My function looks like this:
    function setPackage(str, blah)
    {
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
    {
    alert ("Browser does not support HTTP Request");
    return;
    }
    var url="getVendor.php?";
    url=url+"package="+str;
    url=url+"&partType="+blah;
    url=url+"&sid="+Math.random();
    xmlhttp.onreadystatechange=stateChanged2;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
    }

    Any help would be greatly appreciated.

  • Davide wrote on 25 November, 2009, 2:17

    Hi Roshan,

    a quick question: is it possible to retrieve the after al the selections have been made? I looked at the html code after making the selections, and it only shows the initial state of the options before any selection is made (ie. options for and “Select Country First” and “Select State First”. Any tip?

    Tnx

  • Davide wrote on 25 November, 2009, 2:20

    Quick add:
    I need the option values to save/process the inputs given by the user in the dropdowns.

    Tnx again.

  • vijayan wrote on 28 November, 2009, 5:26

    very nice job thanks exactly get the result

  • Rohit wrote on 3 December, 2009, 13:42

    very useful source for me…

    thanks roshan…

  • Dominik wrote on 13 December, 2009, 2:19

    Does not work =( Roshan pls visit my site and look at the error: http://www.lightbending.webhop.net
    I have download your sourcecode and batch your sql file in mysql 5

  • Leo Zhang wrote on 17 December, 2009, 1:18

    It’s work, but when I apply in my website, it isn’t work….

    I think, the problem is about condition
    –> WHERE countryid=’$countryId’ AND stateid=’$stateId’”;
    Can you explain about that condition?

  • Leo Zhang wrote on 17 December, 2009, 4:11

    Or I send all my code to Mr Roshan, so you can check where the problem is?

  • dee wrote on 27 December, 2009, 14:07

    i figured out a nice 3 dropdown select

    it is working on all browsers but ie6

    i understand it is an onchange issue

    your help thanks

  • tuankaka wrote on 28 December, 2009, 12:05

    Thank you Roshan, i am doing things the same way as you did but my problems is that i am generating the dropdownlist within the backend of joomla frameworks. When the dropdownlist is generated, not only the dropdownlist itself but also the joomla backend banner generated. What can i do with this? Thanks again!

  • zia wrote on 30 December, 2009, 18:44

    still waiting to know about 4 or 5 pair combox box code… i got success in 3 combo box… please no one answered about more than 3 combox box

  • Ben wrote on 5 January, 2010, 20:45

    Is it possible to get the data from box 1 out of mysql database? Just like box 2 and 3

  • Max wrote on 7 January, 2010, 9:05

    Hey Roshan, I tried the code given above but its not working, I mean its not flagging any error but its not working. Whenever I select a country it shows nothing in the state combo list. Though I’ve added some records manually in my database table. but its not retrieving any info. You help would be highly appreciated.

    Thanks in advance!

  • john Tz wrote on 8 January, 2010, 16:43

    I have a problem, if i wanted to post the selected values in to another page i get only the first option country i don know what is the problem because i rembered to put my action page all names are correct, and when i tried to get the values on the same page by removing the action page it works,
    can any one help me

  • kartvizit 15 TL wrote on 9 January, 2010, 13:18

    Refrenced in the blog post is the proof that it is not possible to parse recursive structures with regular expressions. There is no point in arguing about that. Regular expressions might, of course, work in some cases for such examples, but won’t work in every case.

  • Markus P. wrote on 17 January, 2010, 16:00

    I like this script and i was able to get it run. but on the side i need it, i also use moocheck.js and now your script is “disabled”.
    The message i get in Error-console of Firefox:
    “reference to undefined property c.onmousedown
    reference to undefined property c.onmouseup
    reference to undefined property c.onclick”

    Is there a solution for my problem or can you help me?

  • alferg wrote on 20 January, 2010, 7:26

    Hi Roshan, theres no data when i submitted the form.

    Please help

  • Markus P. wrote on 21 January, 2010, 16:59

    Hi Roshan!

    I solved my problem. I only had to change the “onChange” to “onmouseover” like in the moocheck.js and now it is working fine.

  • amit wrote on 26 January, 2010, 17:03

    Hello,

    I download and run the code. But it is not working. Country names are coming. When I select the country from the list the state list is not filled. Please let me know why it is happening.

    Thanks & Regards.

  • Shahab wrote on 28 January, 2010, 7:55

    I want to extend you triple down down using AJAX up to six drop downs in a very similar fashion. So what will i have to do? My deadline is about to reach please do something roshan, I will be very thankful to you.

  • tasha wrote on 31 January, 2010, 23:03

    Hi i have downloaded the zip file containing the source code provided, created the database tables but the state and city drop down list boxex don’t get populated with data as it should…..Any suggestions as to why this happens???

  • gnawz wrote on 15 February, 2010, 14:25

    I have followed the tips on HTML tag placement of forms and tables, however, data in my second drop down is not posted to the dataabase. What else may I do?

  • gnawz wrote on 16 February, 2010, 6:37

    Hi

    I have formatted my HTML tags well but still cannot get the values of the second drop down to post to the database.

    Any more help?

  • danyal wrote on 19 February, 2010, 19:50

    very helpful article… exactly this is what i was lookin for

  • danyal wrote on 19 February, 2010, 19:53

    @tasha:plz check the path of the page that u r calling

  • rutvij wrote on 19 February, 2010, 20:51

    cool tutorial……
    thnx…. it’s easy to understand & implement

  • Mathew Anderson wrote on 3 March, 2010, 22:57

    Great stuff, just what I was looking for. You make ajax very simple to use !

  • n747 wrote on 15 March, 2010, 6:14

    I go through ur tripple drop down ajax based note…It’s really really good…But it not work properly…I also got error not properly load status and city…So If you have corrected code please send me it…Bcz Its very urgent to me…That is great help…

    Thanks dear….You r a real good guy…I appreciate this service..All the Best

  • Vignesh wrote on 21 March, 2010, 8:28

    Thanks a lot friend…………i had to do a little modification on the code, now it works fine, thanks

  • lumz wrote on 25 March, 2010, 18:28

    Thanks man this helped

  • Anil Gomez.D wrote on 26 March, 2010, 11:31

    It’s really really good

  • Anil Gomez.D wrote on 30 March, 2010, 7:03

    Hi Roshan please try

    if i clilck aboutus then print about us details using php ajax

  • karehv wrote on 14 April, 2010, 17:11

    Hi.

    I’m new on php and ajax programming. The tutorial is very friendly and i did all what it saids but it give mi an error.

    There was a problem while using XMLHTTP: Component not found

    Do i have to download or have an extra file fot the ajax to work?

  • Rahul Singh Solanki wrote on 16 April, 2010, 14:39

    i have 2 drop down menu on the same page.
    category & subcategory values are coming from database in
    both drop down menus.
    i want that if i click on a value in the category drop down then sub category drop down’s value should be changed according to it.

Trackbacks

  1. PHP Coding School » Blog Archive » php tips [2008-01-24 12:29:26]
  2. Liste menu ile ilgili - Ceviz Forum
  3. Pacific-Design.com » Populate drop down list box with Ajax
  4. Anonymous
Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.