Now a days Ajax is a most popular technology in web-development field.
Here we will see how can we select country and city dynamically without refreshing a page using ajax.

First create two tables and insert some data into the database.
one table for country and another for city.
The tables structure are given below-

tb_country

country_id country_name
1 India
2 Pakistan
3 USA

here country_id is defined as primary key.

tb_state

state_id country_id state_name
1 1 West Bengal
2 1 Uttar Pradesh
3 2 Lahore
4 3 California

here state_id is defined as primary key.

Now we create total three nos. of pages-
1.connection.php
2.index.php
3.ajax.php

Now lets see the index.php page-

<?php
include connection.php;
$sel_sql="select * from `tb_country`";
$sel_exe=mysql_query($sel_sql);
?>
<html>
<head>
<script language="javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("statediv").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("statediv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php?q="+str,true);
xmlhttp.send(null);
}
</script>

</head>
<body>
<form method=”POST” name=”frm”>
Select Country:-
<select name="country" id="country" onChange="showHint(this.value);">
<option value="0">--Select--</option>
<?php while($sel_rows=mysql_fetch_array($sel_exe))
{
?>
<option value="<?php echo $sel_rows['country_id']; ?>">
<?php echo $sel_rows['country_name']; ?>
</option>
<?php  }   ?>
</select>

Select state:
<div id="statediv">
<select name="state" id="state">
<option>--Select State--</option>
<option></option>
</div>
</form>
</body>
</html>


Now we  make the ajax.php page:-

<?php
include "connection.php";
$country_name = $_GET["q"];
$sql="SELECT * FROM `tb_state` WHERE `country_id`='$country_name'";
$result = mysql_query($sql);
?>
<select name="state" id="state">
<?php
while($row=mysql_fetch_array($result))
{
$id=$row['state_id'];
$state=$row['state_name'];
echo '<option value="'.$id.'">'.$state.'</option>';
}
?>
</select>
Through this code we can select city of the country dynamically without refreshing the page index.php.

Latest posts by rajat

  • Share/Bookmark