Change dropdown list (options) values from database with ajax and php

I’m going to show you a example in php and ajax to change the values of the dropdown’s options without refreshing the page. The values (options) of the dropdown are fetched from the database and the certain portion of the web pages is only refreshed without need to refresh the whole page.


Let’s start with creating the two tables country and city and insert some data

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

Now let’s look at the html code, let’s look at the code of the form and its elements

<form method="post" action="" name="form1">
Country : <select name="country" nChange="getCity('findcity.php?country='+this.value)">
 <option value="">Select Country</option>
 <option value="1">USA</option>
 <option value="2">Canada</option>
     </select>
<br />City : <div id="citydiv">
 <select name="select">
 <option>Select City</option>
     </select>
 </div>
</form>

As you can see that when the dropdown named “country” is changed the “getCity” function is called. Look at the other dropdown carefully, it is inside the division called “citydiv”.

Now let’s look at the javascript function called “getCity”

function getCity(strURL)
{         
 var req = getXMLHTTP(); // fuction to get xmlhttp object
 if (req)
 {
  req.onreadystatechange = function()
 {
  if (req.readyState == 4) { //data is retrieved from server
   if (req.status == 200) { // which reprents ok status                    
     document.getElementById('citydiv').innerHTML=req.responseText;
  }
  else
  { 
     alert("There was a problem while using XMLHTTP:\n");
  }
  }            
  }        
req.open("GET", strURL, true); //open url using get method
req.send(null);
 }
}

now we’ve to create the file called findcity.php and put the following PHP code

<? $country=$_GET['country'];
$link = mysql_connect('localhost', 'root', ''); /change the configuration if required
if (!$link) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax'); //change this if required
$query="select city from city where countryid=$country";
$result=mysql_query($query);?>
<select name="city">
<option>Select City</option>
<? while($row=mysql_fetch_array($result)) { ?>
   <option value><?=$row['city']?></option>
<? } ?>
</select>

Thats all, whenever you change the dropdown of country the values of the city dropdown is automaticalled changed without refreshing the page.
If you want to download full source code, Click here to download.

Security Note : If you want to use this code in your project then there is a security flaw in the PHP code, please use $country=intval($_GET[‘country’]); in the php code instead of $country=$_GET[‘country’]; in the findcity.php to prevent your site from sql injection attack.

117 thoughts on “Change dropdown list (options) values from database with ajax and php

  1. thanku you

  2. Anuj

    The code is good enough. But I have added some functionality to it as I have submitted the form by inserting some extra fields and validations into it. When I submit a form after selecting country and state but keeping other fields unfilled then a validation arises. In this case, country remains selected but the selection of state gets lost. How can I maintain the relationship between country and state after form submission.

  3. online çiçek sipari?iyle ?imdi çiçek göndermek çok daha kolay.çiçekçilik sektörönü sanata dönü?türen tek çiçekçi..

  4. thankyouuuu

  5. Nice script, does just what I was looking for.

    For anyone having those problems with the ajax generated select value not being submitted, you do have to add value=”” to each option.

  6. @Bryson – thanks for the suggestion…….

  7. For sharing thank you very much good very beautiful work

  8. hey there, i was having some problems with the display of options, but i found a solution
    instead of this code:

    Select City

    i added php after the ?, and a ; after each variable, here’s the solution

    Select City

    hope this helps out some fellow programmers (:

  9. thanks

  10. thanks I have found this so informative to me….. thanks alot again …. 😀

  11. Warz

    Thank you, this code was very helpfull :)

  12. great imformatipn

  13. Anas

    Hey,

    After ages of breaking my head, i came across your code, thanks so much!
    Could you help me with this small query though –> Suppose i have a submit button, and i call a js function, How do I pick up the selected value from the city drop down?? I’ve struggled with this with… please help!

    Thanks

  14. Hameed

    Thanks for you article. This will work great if JavaScript is enabled in the browser.

    If JavaScript is disabled in the browser, i want to submit the form with post when the country is changed then in the php file i want to get the country id from the post and filter the cities and update the city fields. Please help me on how to post form data with country id when the country selection is changed.

    I want to use Ajax (if JavaScript is enabled) or form submit (if JavaScript is disabled).

    How can I find out the JavaScript is enabled or not in the browser? I want this functionality in both situations.

    Thanks .

  15. hey hameed checkout this post know how to handle disabled javascript in browser..hope it helps

    http://roshanbh.com.np/2008/04/how-to-know-handle-disabled-javascript.html

  16. john

    Thanks for the code

    my options are usually:

    switch

    how do i get this to work with your tool?

    when i try:

    it doesn’t show the 2nd value in the select box

    thanks

  17. john

    okay, i did actually read the comments – they just didn’t stick in

    so i have a different problem

    i am sending the value to the external php page just fine, and i am using that value for two different queries and two different pull down boxes

    trouble is, i can’t seem to get both select boxes to show up as i want them to

    how do i make sure my divs are separated?

    does that make sense?

    thanks

  18. Meanwhile further tribulations i expect

  19. I was using this for two drop-downs, Make and Model of cars. When I choose ‘Citroen’ or ‘Chrysler’ from the first list nothing would appear in the second but all other makes worked fine. When I changed the query string to ‘citroen’ with a small ‘c’ it worked so I added a strtolower() when outputting the value of the option in the first dropdown.

    This resolved the problem but i have no idea why it happened.

  20. dan

    How would I change the code to be able and populate the first drop down for the database instead of USA
    Canada
    have tried several options and can get it to populate the first drop down but then does not populate the second.

  21. dan

    sorry I mean
    “USA”
    ” Canada”

  22. sorry I mean
    “USA”
    ” Canada”

  23. Kyle

    Hey there!

    Amazing script!!!!

    Question for you, Im trying to use this in connection with another one of my scripts that I use to “duplicate forms”

    essentially I have a form with 2 inputs, that can be “duplicated” when you duplicate the inputs, i have it adding [ ] to the end of each variable in order to be able to have an array caputure data on the other side for each of the inputs, Im having trouble incorporating your script with mine because of the [ ] , do you happen to have a way where I could have multiple of these auto dropdowns on a single page?

  24. Thanks for you article. This will work great if JavaScript is enabled in the browser.

    If JavaScript is disabled in the browser, i want to submit the form with post when the country is changed then in the php file i want to get the country id from the post and filter the cities and update the city fields. Please help me on how to post form data with country id when the country selection is changed.

  25. Selma

    I use your script for a car make /model dropdown. This wroks great, accept for Citroën.
    The first dropdown shows Citroën but the second dropdown shows no models. In the DB there are several models. Looks like it doesn’t recognize Citroën in the DB. Has it something to do with the trema on the e.

    Any solution?

  26. Azmi

    Hey dudes I figured it out. I finally understood. There should be a main table containing all the field controls. And the form tags should be outside that table tags.
    Thanks for this code roshan keep it up…!

  27. Hey dudes I figured it out. I finally understood. There should be a main table containing all the field controls. And the form tags should be outside that table tags.

  28. Thanks for the post, quite a nice tutorial. Will definitely use in the future

  29. Thanks for you article. This will work great if JavaScript is enabled in the browser.

    If JavaScript is disabled in the browser, i want to submit the form with post when the country is changed then in the php file i want to get the country id from the post and filter the cities and update the city fields. Please help me on how to post form data with country id when the country selection is changed.

  30. What about the tables content???
    Anyone has the SQL table code for the entries????

  31. you must have the problem with the dom format i think..just try putting the form tag above the table tag..i.e create the form element first then put tables inside that form, hope this helps

  32. thanks very good !

  33. i love this blog :)

  34. want to submit the form with post when the country is changed then in the php file i want to get the country id from the post and filter the cities and update the city fields. Please help me on how to post form data with country id when the country selection is changed.

  35. Muthu Vijayan

    Not working!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  36. i download your code and modified for me
    actually i wanted to use 2 combo
    1 for Master and another if master A is selected then it will populate
    its correspondence child in second list
    but it will not displaying by using your code
    i m working in php+mysql
    is dere any other code for the same problem

  37. S.SRIVATHSAN

    hei it’s cool and very nice to use. but i need to populate more than one textbox by selecting a value in the drop down list. pls help me. let me clear abt my probs

    by selecting the employee id in the dropdown list, the employee name and employee email id and employee tel no. must be displayed in the corresponding textboxes. kindly help me with your clear cut example style.

  38. Hi
    I got the code to work and would like to open a webpage when the final selection is made. Is this possible ? What additional code would I need.

  39. aarti

    hi all,
    i hv a problem wd this script…
    the 2nd dropdownlist for city is not populating anything after selecting the first one…
    olz help me………

  40. poorni

    can i get code for the contact us from using ajax and php?

  41. poorni

    i need to display the content of contact us form in other page using php and ajax. can anyone help me?

  42. Oug

    Hi all,

    Code is great! But… does anyone know how to pass back a second field? (not only the city name in this example but the city id as well)????

    please heeeeelp !!!!

  43. Thank you very much for everything

  44. thanks very good !

  45. thanks admin very good !

  46. ali

    thank you very much admin good very beautiful work

  47. warhead

    hi, i got this error “object expected”. How to solve this problem? Thanx in advance

  48. Any ideas if there’s a different way of doing this using the JQuery library which will get around the browser issues?

  49. unlucky

    Very nice. I just wonder how could it be for NON mysql

    im total newbie into ajax and js. Could you tell me howto make it without mysql?

    for ex.> USA -> 3 options
    ASIA -> 5 options and so on

  50. Very nice good article Thanks admin

Comments are closed.