Country State City Dropdown Using Ajax | PHP Dev Zone
 

Country State City Dropdown


Today we are going to see how to make triple dropdown of country state and city using ajax.You may have seen this in various sites registration form. When you select any country and according to that country the very next dropdown will populated with that country’s states names.next on selection of the state last dropdown will be filled with the cities of that selected state.



Here one thing that you have to note that this happens without page refresh. To accomplish this we have to use ajax so that page will not get refreshed during selection process.

So let’s have a look behind this whole process how you can made this demo.




First of all we must have the database having three tables for country , state and city.just run the sql statements given below in order to create them.


/* Create table country */
CREATE TABLE `country` (
  `id` tinyint(4) NOT NULL auto_increment,
  `country` varchar(20) NOT NULL default '',
  PRIMARY KEY  (`id`)
)

/*create table state*/
CREATE TABLE `state` (
  `id` tinyint(4) NOT NULL auto_increment,
  `countryid` tinyint(4) NOT NULL,
  `statename` varchar(40) NOT NULL,
  PRIMARY KEY  (`id`)
)

/* Create table city */
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`)
)


Now to test the demo in working we have to add some records in each of the tables. So run the following queries to add the records.

/* Inserting records into country table */
INSERT INTO `country` VALUES (1, 'USA');
INSERT INTO `country` VALUES (2, 'Canada');

/* Inserting records into state table */
INSERT INTO `state` VALUES (1, 1, 'New York');
INSERT INTO `state` VALUES (2, 1, 'Los Angeles');
INSERT INTO `state` VALUES (3, 2, 'British Columbia');
INSERT INTO `state` VALUES (4, 2, 'Torentu');


/* Inserting records into city table */

INSERT INTO `city` VALUES (1, 'Los Angales', 2, 1);
INSERT INTO `city` VALUES (2, 'New York', 1, 1);
INSERT INTO `city` VALUES (3, 'Toranto', 4, 2);
INSERT INTO `city` VALUES (4, 'Vancovour', 3, 2);

Now make one file index.php and paste the below code.

<form method="post" action="" name="form1">
<center>
<table width="45%"  cellspacing="0" cellpadding="0">
  <tr>
      <td width="75">Country</td>
      <td width="50">:</td>
      <td  width="150">
      <select name="country" onChange="getState(this.value)">
<option value="">Select Country</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['id']?>><?php echo $row['country']?></option>
<?php } ?>

     </select>

   </td>

</tr>

<tr style="">

    <td>State</td>

    <td width="50">:</td>

    <td >

<div id="statediv">

        <select name="state" >

       <option>Select State</option>

        </select>

</div>

    </td>
</tr>
<tr>
    <td>City</td>
    <td width="50">:</td>
    <td >
<div id="citydiv">
        <select name="city">
         <option>Select City</option>
           </select>
         </div>
    </td>
  </tr>
  </table>
</center>
</form>

In the onChage event of the country drop down we have called getState() function of the javascript. Which change the options values of 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;
document.getElementById('citydiv').innerHTML='<select name="city">'+
      '<option>Select City</option>'+'</select>';
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}

}

req.open("GET", strURL, true);

req.send(null);

}

}

As you can see in the above code we are passing the countryid to the file findState.php, which populate the options in the drop down of the state which is fetched from Ajax , is given below.


<?php $country=intval($_GET['country']);
$con = mysql_connect('localhost', 'root', ''); 
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('test');
$query="SELECT id,statename FROM state WHERE countryid='$country'";
$result=mysql_query($query);

?>
<select name="state" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select State</option>

<?php while ($row=mysql_fetch_array($result)) { ?>

<option value=<?php echo $row['id']?>><?php echo $row['statename']?></option>

<?php } ?>

</select>

In the above code for the state dropdown, getCity() function is called on its  onChage event having parameters countryId and stateId, 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("Problem while using XMLHTTP:\n" + req.statusText);

}

}

}

req.open("GET", strURL, true);

req.send(null);

}


}

As you can see in the above ajax function, one file 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']);
$con = mysql_connect('localhost', 'root', ''); 
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('test');
$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=<?php echo $row['id']?>><?php echo $row['city']?></option>

<?php } ?>

</select>



UPDATE


If you want to access these Dropdowns values in another form to insert in database or any purpose then what you need to do is,

(1) Define the action in the form of this page.
Example : <form method="post" action="save.php" name="form1">
this means that now submitted form data can be accessed in the file named 'save.php'

(2) so create one file with any name you like or what you have defined in your action.

(3) Now simply write the following code in the newly created file.


if (!empty($_POST))
{
   print_r($_POST);
}

The above code will generate the following output (with values what you have selected from the dropdowns):

Array
(
    [country] => 2
    [state] => 3
    [city] => 4
    [submit] => submit
)


Our task is finished now you can simply access like below,

   $country = $_POST['country'];
   $state   = $_POST['state'];
   $city    = $_POST['city'];


You can now use these variables for what you want.Use them in sql query etc..

That’s it.This is how you can make this type of triple dropdown.Just paste the code in the appropriate files.You can download the full source by the link given below.

Download Full Source


Post a Comment

  1. Nice tutorial.
    Very clear.
    Do you have a solution to save the result (country, state, city selected) inside another table in MySQL.

    Kind regards,
    Remi

    ReplyDelete
    Replies
    1. Thanks for your comments.

      Of course its possible to insert the selected values (from these dropdowns) into other tables.If you need a demo then i will sure send it to you.

      Delete
  2. Dear Ketan,
    Yhank you to reply to me.
    It is very kind.

    I am working on this page:
    http://www.larcebeau.com/contact.php
    I can insert all the fields in a database/table without any trouble, because they are only HTML ==> PHP ==> MySQL fields, using the value '$_POST'.
    The 2 fields I try to manage are: 'Code Postal' and 'Ville'. They are AJAX fields and I need to insert into the same database/table.


    Thank you one more time for your help.
    Kind regards,
    Remi

    I can send you the code.

    ReplyDelete
  3. Dear Ketan,

    I make my script working on my own. The only problem is that I got the 2 fields in arrays format.
    I would prefer a string as a result.
    Do you have any idea.

    As you propose early, I will not mind that you send me a demo.
    If you want I can send you a copy of my script for the help of other people.

    Kind regards,
    Remi

    ReplyDelete
  4. very nice but i have 1 confusion
    first time country state city are selected that's ok but when i select country at second time it do not shows state list it's fine. but it shows the last selected city list which is not from currently selected country.how i can empty the dropdown list of city when country selected second time.

    ReplyDelete
    Replies
    1. Thanks for pointing out this issue.I have updated both the code and source.You can now check it out or download it.

      Delete
  5. First of all thanks a lot for the code, it works like a charm. I need to create another drop down after selecting city... can i ask what if i like to add another drop down after city like schools… do i need to modify the function getXMLHTTP() {}?...can you guide me to proceed further...

    ReplyDelete
    Replies
    1. Yes you can do it.When i got some time i will send you the demo for the same.

      Delete
  6. Awesome Code! I had been working on this for a week, with limited success! I want to use it in an Itinerary so I need two sets of drop downs. One for departure, one for arrival. I basically duplicated your form, the FindCity and findState.php files, and the getCity, getState functions, changing all the required names and references, I think.

    The only problem is the second Country select does not populate, even if I select it first. The only way I can get it to work is if I delete the 1st Country select completely. When I do the entire second form works perfect, making me thing I got all my new references correct. Of course the first form is now dead!

    What could stop the second country select from populating? I don't see anything in your code that should cause this, of course I know just enough to be dangerous!

    Thanks in advance for any help you can provide, and thanks again for the great form.

    ReplyDelete
    Replies
    1. Thanks for reading the post.

      I'm not exactly sure what you've implemented but i think it was due to two same ids.It would be better if you send me the db schema and the files you're working on and i'll try to sort it out your problem.

      Delete
  7. Hi Ketan!
    Thanks for the code, very useful. I have a question on using the selected value for the next stage, in a form, which is then processed in to do a database via sql. Once the country, state and city has been loaded, how do i then access these variables? E.g. say use a submit button to post these? Any help would be much appreciated! Thanks!

    ReplyDelete
    Replies
    1. Hi Priyan,

      Thanks for reading the post.I have updated the post to answer your question.I hope you'll easily understand what to do and it will solve what you want to do.If you have any query then feel free to comment here.

      Delete
    2. Wow! Thanks very much for your help! This will help me a lot! Appreciate your code and comments!

      Delete
    3. hi Ketan,
      Very useful code, i tried and it worked. I have one query, i have used this fields with other fields in my form and after submitting the form i am NOT able to retain state and city dropdown values (i am able to retain country dropdown value). May be the reason is because when page relaods, form state and city in index.php have only one default value. Any idea how to retain state and city dropdown values?

      Delete
  8. Hi Bhavesh,

    I have already added new UPDATE at the end of the post which shows how you can get the selected values after form submission.However i have sent mail to you regarding this issue.But as many other readers also facing the same kind of issue, soon i will add demo for the complete form including this dropdowns to get better understanding of the concept.Feel free to ask any questions.

    Thanks for reading article on PHP Dev Zone.

    ReplyDelete
  9. Hi Ketan,
    That was again very helpful. How do we get text again the value we get from post.

    ReplyDelete

 
Top