Change drop-down list (options) values from database with ajax and php
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-
Select state:
<div id="statediv">
<select name="state" id="state">
<option>--Select State--</option>
<option></option>
</div>
</form>
</body>
</html>
<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>
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>
Latest posts by rajat
- To create a password meter using Javascript - September 21st, 2011
- Creating a Simple pop-up with blocked background - August 30th, 2011
