AJAX (Asynchronous JavaScript and XML) is a method of building pages for the Web that process user requests immediately. What this means is that you can use AJAX to change a small part of the page in response to something that the user does, instead of reloading the entire page.
AJAX combines several programming tools including:
All of the major browsers now support the XMLHttpRequest object, so AJAX is gaining in popularity and wider usage on Web sites.
The sample code in this handout will show you one way to make a Web page which has these features:
You can see the form page running here. This is page AjaxForm5.php, which we will see (along with the other pages, too) in the following sections.
The form page is AjaxForm5.php:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Dynamically Populate a Select List</title>
<link rel="stylesheet" type="text/css" media="all" href="PHPstyles.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({url:"getCategoryInfo5.php",
type: "get",
datatype: "json",
success:function(result){
var selectContents = "";
selectContents += '<option value="0">-- Select a Category --</option>';
var theCategories = $.parseJSON(result);
console.log(theCategories);
var theRows = theCategories.rows;
console.log("Number of rows: " + theRows.length);
for (var i = 0; i < theRows.length; i++) {
selectContents += "<option value='" + theRows[i].category_id + "'>" + theRows[i].category_name + "</option>";
}
$("#categoryID").html(selectContents);
}
});
$('#categoryID').on("change", function()
{
$.ajax({url:"getCategoryDetailInfo5.php?categoryID=" + $(this).val(),
type: "get",
datatype: "json",
success:function(result){
var selectContents2 = "";
selectContents2 += '<option value="0">-- Select a Category Item --</option>';
var theItems = $.parseJSON(result);
var theRows2 = theItems.rows;
for (var i = 0; i < theRows2.length; i++) {
selectContents2 += "<option value='" + theRows2[i].category_detail_id + "'>" + theRows2[i].category_detail_name + "</option>";
}
$("#categoryDetail").html(selectContents2);
}
});
});
$(document).on("change", "#categoryDetail", function()
{
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
$('#youSelected').html(textSelected);
});
});
</script>
</head>
<body>
<div id="mainDiv">
<form>
<input type="hidden" name="categoryDetailID" value="" />
<table>
<tr>
<td>Select a Category: </td>
<td>
<select name="categoryID" id="categoryID">
</select>
</td>
</tr>
<tr>
<td>Select a Category Item: </td>
<td>
<select name="categoryDetail" id="categoryDetail">
<option value="0">-- Select a Category Item --</option>
</select>
</td>
</tr>
<tr>
<td>You selected: </td>
<td>
<div id="youSelected">
</div>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
The first query page, which is used by the first jQuery.ajax() call in the form page, is getCategoryInfo5.php:
<?php
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
//ini_set('memory_limit', '1024M'); // or you could use 1G
require 'includes/config.php';
require 'includes/helperStuff.php';
$mysqli = new mysqli(DBSERVER, DBUSER, DBPWD, DBNAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM Category ORDER BY category_name";
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
$resultsArray = array();
$rowInfo = $result->fetch_assoc();
while ($rowInfo != null)
{
$resultsArray[] = $rowInfo;
$rowInfo = $result->fetch_assoc();
}
$resultsObj = new stdClass();
$resultsObj->rowcount = count($resultsArray);
$resultsObj->rows = $resultsArray;
echo json_encode($resultsObj);
?>
The second query page, which is used by the second jQuery.ajax() call in the form page, is getCategoryDetailInfo5.php:
<?php
require 'includes/config.php';
$mysqli = new mysqli(DBSERVER, DBUSER, DBPWD, DBNAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$categoryID = $_REQUEST["categoryID"];
$query = sprintf("Select *
From Category_Detail
Where category_id = %d
Order by category_detail_name",
$categoryID);
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
$resultsArray = array();
$rowInfo = $result->fetch_assoc();
while ($rowInfo != null)
{
$resultsArray[] = $rowInfo;
$rowInfo = $result->fetch_assoc();
}
$resultsObj = new stdClass();
$resultsObj->rowcount = count($resultsArray);
$resultsObj->rows = $resultsArray;
echo json_encode($resultsObj);
?>
Please note these points about the above sample code:
$('#categoryID').on("change", function() and it makes
the second jQuery.ajax() call to the second query page, getCategoryDetailInfo.php, when the
list's selection is changed.
$.ajax({url:"getCategoryDetailInfo5.php?categoryID=" + $(this).val()
The code $(this).val() is jQuery code in the form page
which gets the categoryID value of the selected <option> tag.
$resultsObj = new stdClass();
echo json_encode($resultsObj);converts the PHP array into a "JavaScript Object Notation" (JSON) string by using the built-in PHP function json_encode(), and then uses echo() to send the JSON-encoded string back to the ajax() call in the form page.