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 sit
you need to send your response in a single string. So make a string of all teachers returned by query.
And then in your ajax part,split this this string.
change your query in getTeacher.php page to. $sql="SELECT * FROM departments WHERE departmentName = '$q'";
I remember doing my first Ajax request with Jquery and found it hard to find a good complete example as well, especially something with error handling (how can I tell the user if something goes wrong in the backend, e.g. the database is not available?).
Here's your code rewritten using PDO and Jquery including some error handling (I did not use the Mysql extension as it is removed from recent PHP versions (btw, your code is open to sql injection, it is very easy to drop your database):
<!DOCTYPE html>
<html>
<head>
<title>Selectbox Ajax example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
<div id="error"></div>
<select name="department_list" id="department_list">
<option value="department1">Department 1</option>
<option value="department2">Department 2</option>
</select>
<div id="txtTeachers">Teacher names</div>
<div id="result">
<ul id="list">
</ul>
</div>
<script type="text/javascript">
$(document).ready(function () {
// if user chooses an option from the select box...
$("#department_list").change(function () {
// get selected value from selectbox with id #department_list
var selectedDepartment = $(this).val();
$.ajax({
url: "getTeachers.php",
data: "q=" + selectedDepartment,
dataType: "json",
// if successful
success: function (response, textStatus, jqXHR) {
// no teachers found -> an empty array was returned from the backend
if (response.teacherNames.length == 0) {
$('#result').html("nothing found");
}
else {
// backend returned an array of names
var list = $("#list");
// remove items from previous searches from the result list
$('#list').empty();
// append each teachername to the list and wrap in <li>
$.each(response.teacherNames, function (i, val) {
list.append($("<li>" + val + "</li>"));
});
}
}});
});
// if anywhere in our application happens an ajax error,this function will catch it
// and show an error message to the user
$(document).ajaxError(function (e, xhr, settings, exception) {
$("#error").html("<div class='alert alert-warning'> Uups, an error occurred.</div>");
});
});
</script>
</body>
</html>
PHP part
<?php
// we want that our php scripts sends an http status code of 500 if an exception happened
// the frontend will then call the ajaxError function defined and display an error to the user
function handleException($ex)
{
header('HTTP/1.1 500 Internal Server Error');
echo 'Internal error';
}
set_exception_handler('handleException');
// we are using PDO - easier to use as mysqli and much better than the mysql extension (which will be removed in the next versions of PHP)
try {
$password = null;
$db = new PDO('mysql:host=localhost;dbname=iobserve', "root", $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// note the quote thing - this prevents your script from sql injection
$data = $db->query("SELECT teacherName FROM departments where departmentName = " . $db->quote($_GET["q"]));
$teacherNames = array();
foreach ($data as $row) {
$teacherNames[] = $row["teacherName"];
}
// note that we are wrapping everything with json_encode
print json_encode(array(
"teacherNames" => $teacherNames,
"anotherReturnValue" => "just a demo how to return more stuff")
);
} catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}