Monday, 11 February 2013

JQuery: Ajax Example of Select Values Filled Dynamically


Make Dynamic Select Box using Ajax, Jquery, Php, MySql.
First Choose country from Select Box of country after that pull data from database using Ajax, Jquery and show data other Select box of city without page refresh.
Requirements:
1)index.php
2)city.php
3)tables in a database.
  • country
  • city
Two tables are required
index.php
________________________________________________________________________________
java script code
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function(){
$(“.country”).change(function(){
$id = $(this).val();
$.ajax({
type:”Post”,
url:”city.php”,
data:”id=”+$id,
cache:”false”,
success:function(html){
$(“#city”).html(html);
}
});
});
});
</script>
Php code
<div class=”label”>Country</div>
<select class=”country”>
<option selected=”selected”>Select Country</option>
<?php
include(“config.php”);
$sql = “select * from country” or die(“query error”);
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$id = $rows['id'];
$country = $rows['country'];
echo ‘<option value=”‘.$id.’”>’.$country.’</option>’;
}
?>
</select>
Html code
<div class=”label”>City</div>
<select id=”city”>
<option value=”"<Select Country first</option>
</select>
________________________________________________________________________________

City.php

_________________________________________________________________________________

<?php
include(“config.php”);
$sql = “select id,city from city where country_id=”.$_POST['id'] or die(“query error”);
$result = mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$cityid= $rows['id'];
$cityname = $rows['city'];
echo ‘<option id=”‘.$cityid.’”>’.$cityname.’</option>’;
}
?>
__________________________________________________________________________________________



No comments:

Post a Comment

Search Engine Submission - AddMe