i am new to php and i have the following problem:
i have two drop down lists and the following code is to change the values of the dropdown’s options without refreshing the page using Ajax.The first dropdown is working fine and the problem is that the cities dropdown that is populated from the countries dropdown is not working, so i need to know where is the problem
The values (options) of the dropdown are fetched from the database, the two tables countries and cities are :
Code: Select all
create table Countries(
Country_Id int not null auto_increment,
Constraint PK_Cou_Id primary key (Country_Id),
Country varchar(30)not null,
Country_Code varchar(5) not null
)
create table Cities(
City_Id int not null auto_increment,
constraint PK_City_Id primary key (City_Id),
Country_Id int not null,
constraint FK_Cou_Id foreign key (Country_Id) references Countries(Country_Id),
City varchar(30)not null
)
Code: Select all
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
<script type="text/javascript">
function loadCities(countryid)
{
if(countryid="")
{
document.getElementById("cities".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("cities").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_cities.php?countryid="+countryid,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div class="page">
<form method="post" name="form1">
<div id="main">
<table>
<tr>
<td>
<label>Country</label>
</td>
<td>
<?php
$db=mysql_connect("localhost","root");
mysql_select_db("EMA");
$result=mysql_query("select * from Countries",$db);
?>
<select name="countries" id="countries" onChange="loadCities(this.value)" >
<?php
while($row=mysql_fetch_array($result))
{
?>
<option value=" <?php echo $row['Country_Id']?>" >
<?php echo $row['Country']?>
</option>
<?php
} ?>
</select>
</td>
<td>
<label>City</label>
</td>
<td>
<div id="citydiv">
<select name="city">
<option>Select City</option>
</select>
</div>
</td>
</tr>
</table>
</div>
</form>
</div>
</body>
</html>
this file is findcities.php that fetch the
Code: Select all
<?PHP
$countryid=intval($_GET['countryid']);
$con=mysql_connect("localhost","root");
if(!$con)
{
die("Could not connect to mysql database due to :". mysql_error());
}
mysql_select_db("EMA",$con);
$query="select * from Cities where Country_ID = '$countryid'" ;
$result=mysql_query($query);
?>
<select name="city" >
<option>Select City</option>
<?php
while($row=mysql_fetch_array($result))
{ ?>
<option value=<?php echo "'.$row['City_Id'].'"?> >
<?php echo $row['City']?>
</option>
<?php } ?>
</select>
is the order of the form ,table and div tags affect that or what.