I know that this is a popular question and I have looked at many examples trying to get my head around AJAX
and jQuery
.
I have a simple situation with one drop down box when changed sends an AJAX
request for the results of an SQL
query based on the drop down box selection.
The page loads correctly and the function is being called when a department is being chosen from the drop down box (the alert tells me that) but I am not getting any return data. In trying to identify the problem how can I tell whether the getTeachers.php file is actually running?
Web page Script for calling getTeacher.php on the server
<script src="http://localhost/jquery/jquery.min.js">
</script>
<script>
function checkTeacherList(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtTeacher").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtTeacher").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getTeachers.php?q="+str,true);
xmlhttp.send();
alert(str); //To test it is getting this far, which it does
}
</script>
Drop down box and txtTeacher ID for return data from server
<select name="department_list" id="department_list" onchange="checkTeacherList(this.value);" >
<?php
$options[0] = 'All';
$intloop = 1;
while($row = mysql_fetch_array($department_result))
{
$options[$intloop] = $row['departmentName'];
$intloop = $intloop + 1;
}
foreach($options as $value => $caption)
{
echo "<option value=\"$caption\">$caption</option>";
}
?>
</select>
<div id="txtTeachers">Teacher names</div>
Server side PHP - getTeachers.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error($con));
}
$db_selected = mysql_select_db("iobserve");
$sql="SELECT * FROM departments WHERE departmentName = '".$q."';";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['teacherName'];
}
mysql_close($con);
?>