So I am trying to have a website update state and city lists from a server.
My code for states seems to work fine, the problem I have is with updating the city list. I adapted an answer from here earlier, and it doesn't seem to work, although that is most likely my fault.
here is the state php code.
<?php
$con= mysqli_connect($host, $user, $pass, $database);
if($debug){
echo $host,$user,$pass,$database;
}
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$states = '';
$resultState = mysqli_query($con,"SELECT DISTINCT State FROM CitiesStates");
while($row = mysqli_fetch_array($resultState))
{
if($debug){
echo $row['State'];
}
$states .="<option>" . $row['State'] . "</option>";
}
$statesDrop="
<p><label>States</label></p>
<select name='States' id='States' onchange='getCity(this.value))'>
" . $states . "
</select>";
echo $statesDrop;
mysqli_close($con);
?>
so on selection it should call this function.
<script type="text/javascript">
function getCity(stateId)
{
var strURL="findCity.php?state="+stateId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:
" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
which calls this php file.
$stateId=intval($_GET['state']);
$con= mysqli_connect($host, $user, $pass, $database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Cities = '';
$resultCity = mysqli_query($con,"SELECT City FROM CitiesStates WHERE State='$stateId'");
while($row = mysqli_fetch_array($resultCity))
{
if($debug){
echo $row['City'];
}
$Cities .="<option>" . $row['City'] . "</option>";
}
$citiesDrop="
<p><label>Cities</label></p>
<select name='Cities' id='Cities' onchange=''>
" . $Cities . "
</select>";
echo $citiesDrop;
mysqli_close($con);
?>
Additionally my getXMLhttp() function, since this seems to be the problem
function getXMLHTTP() {
var x = false;
try {
x = new XMLHttpRequest();
}catch(e) {
try {
x = new ActiveXObject("Microsoft.XMLHTTP");
}catch(ex) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1) {
x = false;
}
}
}
return x;
}
I think it is due to this in findCity.php
$citiesDrop="
<p><label>States</label></p>
<select name='States' id='States' onchange='getCity(this.value))'>
" . $states . "
</select>";
It looks like you copied it from your state php code, but did not update it correctly. You php page is probably sending a req.status of 500, as $states
is not defined. Try updating to -
$citiesDrop="
<p><label>Cities</label></p>
<select name='Cities' id='Cities'>
" . $Cities . "
</select>";