Dynamically Populate Select List by Ajax

Many times, when your data is based on one parameter then you have to submit your form with user given input for getting the data based on given input by user. This increase waiting time for user completing input and adds extra request/response trip also. For this kind of situation, Ajax has provided great choice to site owner.
So, here we will create dynamic list of cities based on selected country by user. As soon as user selects their choice of country they will get list of cities of the selected country.
This HTML page will be provided to user for selecting country-
Page::dynamic_city_state.php

<?php
print_r($_POST); // print all the post-ed data. For testing
?>
<html>
<head>
 <title>Country City List</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src="ajax_req.js" type="text/javascript"></script>
</head>
<body>
<form method="post">
<!-- Ajax call to city page -->
<select name="country" onchange="htmlData('city.php', 'ch='+this.value)" />
  <option value="#">-Select-</option>
  <option value="India">India</option>
  <option value="USA">USA</option>
</select>
<div id="txtResult"> <select name="cityList"><option></option></select> </div>
<input type="submit" />
</form>
</body>
</html>

Familiar JavaScript Ajax Script will be used for dynamically populating select list! -

page:ajax_req.js


function GetXmlHttpObject(handler)
{
   var objXMLHttp=null
   if (window.XMLHttpRequest)
   {
       objXMLHttp=new XMLHttpRequest()
   }
   else if (window.ActiveXObject)
   {
       objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
   }
   return objXMLHttp
}
function stateChanged()
{
   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
   {
           document.getElementById("txtResult").innerHTML= xmlHttp.responseText;
   }
   else {
           //alert(xmlHttp.status);
   }
}
// Will populate data based on input
function htmlData(url, qStr)
{
   if (url.length==0)
   {
       document.getElementById("txtResult").innerHTML="";
       return;
   }
   xmlHttp=GetXmlHttpObject()
   if (xmlHttp==null)
   {
       alert ("Browser does not support HTTP Request");
       return;
   }
   url=url+"?"+qStr;
   url=url+"&sid="+Math.random();
   xmlHttp.onreadystatechange=stateChanged;
   xmlHttp.open("GET",url,true) ;
   xmlHttp.send(null);
}
This PHP page will be called by Ajax-
page::city.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// List of cities for India
if ($_GET['ch'] == 'India') {
   ?>
<select name="cityList">
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
<option value="Bangalore">Bangalore</option>
<option value="Patna">Patna</option>
</select>
<?php
}
// List of cities for USA
if ($_GET['ch'] == 'USA') {
   ?>
<select name="cityList">
<option value="Albama">Albama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="Florida">Florida</option>
</select>
<?php
}
?>

If you came here for country->City and "IP" mapping then your destination is this: Country/City IP mapping

  • # 1 - by dsfdsaf

    I have been trying for a long time to solve a certain problem. What I need is to dynamically populate a select menu with options from a MySQL table. However, the options stored in a cell with comma delimiters. For example, option A, option B. What I need now is to separate the options into separate strings (2+) and place them as:Note: I could not use brackets, so I used parentheses.(opening select)(opening option)option A(closing option)(opening option)option B(closing option)(closing select)Thanks for your help.

  • # 2 - by Satya Prakash Karan

    This kind of questions are best suited at PHP forum. Register at any good forum – The Scripts, OZZU, etc

  • # 3 - by Satya Prakash Karan

    This kind of questions are best suited at PHP forum. Register at any good forum – The Scripts, OZZU, etc

  • # 4 - by Ando

    The code works fine in generally, but I noticed one problem with Firefox (while OK with IE):

    when the form elements are separated into different cells of the table for designing the layout, then the form does not seem to recognize the loaded value from the city’s select box.

    There have never been any problems before with static form elements being separated into different table cells, but apparently this dynamic ajax version does not function well in table cells.

    Any suggestions or comments?

  • # 5 - by Ando

    The code works fine in generally, but I noticed one problem with Firefox (while OK with IE):when the form elements are separated into different cells of the table for designing the layout, then the form does not seem to recognize the loaded value from the city’s select box. There have never been any problems before with static form elements being separated into different table cells, but apparently this dynamic ajax version does not function well in table cells.Any suggestions or comments?

Comment pages
1 4 5 6 7 8 200
Comments are open for an year period. Please, write here on Facebook page.