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
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):
Selectbox Ajax example
Teacher names
PHP part
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();
}