Lec 10-Ajax
Lec 10-Ajax
Content
v Basic objects necessary
v Setting up the XMLHttpRequest object
v Making the call
v How the server responds
v Using the reply
v XML basics
The usual way we operate in the Web
v Typical browsing behaviour consists of loading a web page,
then selecting some action that we want to do, filling out a
form, submitting the information, etc.
v This object is not yet part of the DOM (Document Object Model)
standard, but is supported (in different fashions) by Firefox,
Internet Explorer, Safari, Opera, and other popular browsers.
v The main idea is that the properties are set after the object is
created to specify information to be sent to the server, as well
as how to handle the response received from the server. Some
properties will be updated to hold status information about
whether the request finished successfully.
v The methods are used to send the request to the server, and to
monitor the progress of the request as it is executed (and to
determine if it was completed successfully).
XMLHttpRequest object properties
Property Description
v readyState An integer from 0. . .4. (0 means the call
is uninitialized, 4 means that the call is
complete)
v onreadystatechange Determines the function called when the
objects readyState changes.
v responseText Data returned from the server as a text
string (read-only).
v responseXML Data returned from the server as an XML
document object (read-only).
v status HTTP status code returned by the server
v statusText HTTP status phrase returned by the server
The open object method is used to set up the request, and the send method starts
the request by sending it to the server (with data for the server if the POST
method is used).
A general skeleton for an Ajax application
<script type="text/javascript">
// ***** include the getXMLHttpRequest function defined before
var ajaxRequest = getXMLHttpRequest();
if (ajaxRequest) { // if the object was created successfully
ajaxRequest.onreadystatechange = ajaxResponse;
ajaxRequest.open("GET", "search.php?query=Bob");
ajaxRequest.send(null);
}
function ajaxResponse() //This gets called when the readyState changes.
{
if (ajaxRequest.readyState != 4) // check to see if we’re done
{ return; }
else {
if (ajaxRequest.status == 200) // check to see if successful
{ // process server data here. . . }
else {
alert("Request failed: " + ajaxRequest.statusText);
}
}
}
</script>
A first example
v Here’s an example to illustrate the ideas we’ve mentioned (inspired by
an example in the book Ajax in 10 Minutes by Phil Ballard).
v The main idea is that we’re going to get the time on the server and
display it to the screen (and provide a button for a user to update this
time). The point I want to demonstrate here is how to use Ajax to do
this update without updating/refreshing the entire webpage.
v We use a (very) small PHP script to get the date from the server, and
return it as a string as a response to the request. Here is the script:
<?php
echo date('H:i:s');
?>
<form>
<input type="button" value="Get Server Time"
onclick="getServerTime();" />
</form>
<div id="showtime" class="displaybox"></div>
</body>
</html>
view the output page
v Thus, you can send back a simple text string as the first example did, or you
could send a string with HTML tags embedded in it. You can process the string
using JavaScript functions (to split it into substrings, add/delete parts of it,
etc.).
v You could even send back a string that has JavaScript code it in and execute it
using the JavaScript eval() method.
Example with HTML tag (Change the PHP script to insert HTML tags.)
v After that change (and inserting the new script name into the HTML
code), we need to alter the ajaxResponse function to parse the XML
document. That new JavaScript function is given on the next slide.
v Note that we need not explicitly create an object to hold the XML
document, but that responseXML (as a property of XMLHttpRequest)
is already such an object.
The new Ajax response function
function ajaxResponse() //This gets called when the readyState changes.
{
if (ajaxRequest.readyState != 4) // check to see if we're done
{ return; }
else {
if (ajaxRequest.status == 200) // check to see if successful
{ var timeValue = ajaxRequest.responseXML.
getElementsByTagName("timenow")[0];
document.getElementById("showtime").innerHTML =
timeValue.childNodes[0].nodeValue; }
else {
alert("Request failed: " + ajaxRequest.statusText);
}
}
}
v This new response function uses a JavaScript method to access the XML DOM and
retrieve the time string before inserting it into the output display box.
<head>
<title>Ajax Demonstration</title>
<style>
</style>
<script>
// The JavaScript front end will be in here.
</script>
<body>
<h1>Ajax Demonstration of Live Search</h1>
<p>
Search for: <input type="text" id="searchstring" />
</p>
<div id="results">
<ul id="list">
<li>Results will be displayed here.</li>
</ul>
</div>
v This PHP script takes the query that will be passed to it, then searches for (case insensitive)
matches to the names in the array.
v It passes an XML document back to the calling function consisting of the names that it finds.
The JavaScript functions
v We obviously need the function for creating a new XMLHttpRequest
object, which we will store in a global variable called “ajaxRequest”.
v The search will be handled by setting up a Timeout event, based on
entering text in the input field (using the “onkeydown” attribute).
var t; // public variable for the timeout
function startSearch()
{
if (t) window.clearTimeout(t);
t = window.setTimeout("liveSearch()",200);
}
v The “liveSearch” function is the main calling routine, where we set up
the XMLHttpRequest object, and make the call to the PHP script.
The JavaScript functions (cont.)
Recall that we’re making ajaxRequest a global variable in the script, so
that as in the other example we can access it’s properties in the
callback function.
function liveSearch()
{
ajaxRequest = getXMLHttpRequest();
if (!ajaxRequest) alert("Request error!");
var myURL = "search.php";
var query = document.getElementById("searchstring").value;
myURL = myURL + "?query=" + query;
ajaxRequest.onreadystatechange = ajaxResponse;
ajaxRequest.open("GET", myURL);
ajaxRequest.send(null);
}
if($query != "")
{
include_once('db_access.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if(!$connection)
{
exit("Could not connect to the database: <br/>" .
htmlspecialchars(mysql_error));
}
mysql_select_db($db_database);
mysql_close($connection);
}
echo "</names>";
view the output page
?>
Some cautions
v As with any JavaScript element, you can’t (or shouldn’t) rely
upon a user’s browser being able to execute JavaScript (some
people turn it off on their browsers). (Of course, there are
webpages that ignore this caution.)