article

Sunday, June 2, 2013

Drop-down select from database with ajax and php

Drop-down select from database with ajax and php

 Download

//index.php
<?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>
<br/>
Select state:
<div id="statediv">
<select name="state" id="state">
<option>--Select State--</option>
<option></option>
</div>
</form>
</body>
</html>
//connection.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "ednalan";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>
//ajax.php
<?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>

Related Post