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 Alen S

    Hi!
    I need the same script but my data is in an SQL database.
    One Database contains the Country
    The other database(users database profile) contains the Country ID (eg.1,2,3) and a name of the city

    I would need to to a select from the first database to get a list of the country..and for the latter a select from (users table) where county=X…

    i know i did not described it well..but..i hope you did got it

  • # 2 - by Alen S

    Hi!I need the same script but my data is in an SQL database.One Database contains the CountryThe other database(users database profile) contains the Country ID (eg.1,2,3) and a name of the cityI would need to to a select from the first database to get a list of the country..and for the latter a select from (users table) where county=X…i know i did not described it well..but..i hope you did got it

  • # 3 - by Satya Prakash Karan

    No problem.
    It is same. just use a query for generating country list on Page::dynamic_city_state.php. and instead of passing countryCode pass country id in $_GET[‘ch’]. And on city page you can check which country id it is?
    Something like:
    if (isset($_GET[‘ch’])) {

    $cID = (integer)$_GET[‘ch’];

    $rst = mysql_query(“select id, cname from countryCity where id=$cID”);
    if row count > 0 {
    echo ‘<select name=”cityList”>’;
    while (…) {
    // generate data like
    /*
    <option value=”Mumbai”>Mumbai</option>
    <option value=”Delhi”>Delhi</option>
    */
    }
    echo ‘</select>’;
    }
    }

  • # 4 - by Satya Prakash Karan

    No problem.It is same. just use a query for generating country list on Page::dynamic_city_state.php. and instead of passing countryCode pass country id in $_GET[‘ch’]. And on city page you can check which country id it is?Something like:if (isset($_GET[‘ch’])) {$cID = (integer)$_GET[‘ch’];$rst = mysql_query(“select id, cname from countryCity where id=$cID”);if row count > 0 {echo ‘<select name=”cityList”>’; while (…) { // generate data like /*<option value=”Mumbai”>Mumbai</option> <option value=”Delhi”>Delhi</option> */ }echo ‘</select>’;}}

  • # 5 - 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.

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