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. thanks for all it is very nice blog

  2. cmycll

    Very simple and descriptive narration. Thank you very much.

  3. Ron

    3 years after you share your code, I find it and download source files. It works great! I googled so much I got warnings it though I was a bot, lol. Yours was the only ajax/php code I found for populating a dropdown box while not requiring the php echo function. You are very talented. Thank you so much for sharing it with all of us. :)

  4. 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.

  5. 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….

  6. hi
    I’m really very useful to follow a long-time see this as a blog here Thank you
    for your valuable information.

  7. Josh

    Thank you very much for this tutorial. Keep up the good work.

  8. Yusuff

    Thanks a lot man, I’m really new to AJAX, and I wanted to do a similar function in my project and I was searching everywhere to know the easiest and understandable method, and yeah I found YOU and YOUR methods, nice man! .

  9. Very good!You help me so much with this code.Life it’s easily.

  10. Saj

    Hey Roshan… Thanks alot for the code… really helped!!

  11. great work! thanks…

  12. vishal

    Hey i’m new to AJAX n PHP…im usin ur code but my city list is not getting polpulated…so wht shud i do…i guess it’s bcoz u have not mention the path for findcity.php in index.php…n i hav gone through some comment…but cudnt get the answer…

  13. dev

    Wen i submitting the form, if error occur because of validation ,not getting the value i selected in city. how to retain values in dropdown list after refreshing ? pls help me.

  14. zeeshan

    man u rock . thanks

Comments are closed.