Lecture 5 - Ajax
Lecture 5 - Ajax
Lecture 5 - Ajax
Ajax
Outlines:
Basic objects necessary
XML basics
The usual way we operate in the Web
Typical browsing behaviour consists of loading a web page, then
time, and have to wait for the server to respond, loading a whole
new web page before we continue.
This is also one of the limitations of web pages, where
One of the limitations of JavaScript is (or used to be) that there was no
way to communicate directly with a web server.
XMLHttpRequest object
The heavy lifter for Ajax: It’s a javascript object embedded in most modern browsers that
sets up data request/response pipelines between client and server.
Javascript
Lightweight programming language that Ajax uses for instructions to bind all of the
components together.
How Ajax Works
Classic XHTML form: User submits entire form to server, which validates the data entered (if any).
Server responds indicating fields with invalid or missing data.
Ajax-enabled form shows errors asynchronously when user moves to another field.
Potential Problems
Javascript MUST be enabled
This back end could be simply a file that the server passes back to the
and POST methods to the server in the same way that an HTML
form sends information.
Recall from our previous discussions that the GET request
Firefox, Safari, Opera, and some other browsers can create one of
these objects simply using the “new” keyword.
<script type=“text/javascript”>
ajaxRequest = new XMLHttpRequest();
</script>
The XMLHttpRequest object (cont.)
Microsoft Internet Explorer implements this object using its
proprietary ActiveX technology. This requires a different syntax
for creating the object (and can also depend upon the particular
version of Internet Explorer being used).
To handle different types of browsers, we use the
try { . . . } catch (error) { . . . } format.
The “try” section attempts to execute some JavaScipt code. If an
error occurs, the “catch” section is used to intervene before the
error crashes the JavaScript (either to indicate an error has
happened, or to attempt something else).
To create one of these objects we can use a sequence of try. . . catch
blocks, attempting different ways to create an XMLHttpRequest
object.
function getXMLHttpRequest()
/* This function attempts to get an Ajax request object by trying
a few different methods for different browsers. */
{
var request, err;
try {
request = new XMLHttpRequest();// Firefox, Safari, Opera,etc.
}//try
catch(err) {// catch 1
try { // first attempt for Internet Explorer
request = new ActiveXObject("MSXML2.XMLHttp.6.0");
}//try
catch (err) {// catch 2
try { // second attempt for Internet Explorer
request = new ActiveXObject("MSXML2.XMLHttp.3.0");
}//try
catch (err) { // catch 3
request = false; // oops, can’t create one!
}// catch 3
} //catch 2
} //catch 1
return request;
}// function
{
if (ajaxRequest.readyState != 4) // check to see if we’re done
{ return; }//if
else {
if (ajaxRequest.status == 200) // check to see if successful
{ // process server data here. . . }//if
else {
alert(“Request failed: “ + ajaxRequest.statusText);
}//else
}//else
}//function
</script>
A first example
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.
We use a (very) small PHP script to get the date from the server, and
<head>
<title>Ajax Demonstration</title>
<style>
body {
background-color: #CCCCCC;
text-align: center;
}
.displaybox {
margin: auto;
width: 150px;
background-color: #FFFFFF;
border: 2px solid #000000;
padding: 10px;
font: 1.5em normal verdana, helvetica, arial, sans-
serif;
}
</style>
<script type="text/javascript">
var ajaxRequest;
function getXMLHttpRequest()
/* This function attempts to get an Ajax request object by trying
a few different methods for different browsers. */
{
// same code as before. . .
}
ajaxRequest.responseText; }
else {
alert("Request failed: " + ajaxRequest.statusText);
}
}
}
function getServerTime() // The main JavaScript for
calling the update.
{
ajaxRequest = getXMLHttpRequest();
if (!ajaxRequest) {
document.getElementById("showtime").innerHTML =
"Request error!";
return; }
var myURL = "telltime.php";
var myRand = parseInt(Math.random()*999999999999999);
myURL = myURL + "?rand=" + myRand;
ajaxRequest.onreadystatechange = ajaxResponse;
ajaxRequest.open("GET", myURL);
ajaxRequest.send(null);
}
</script>
</head>
<body onLoad="getServerTime();">
<h1>Ajax Demonstration</h1>
<h2>Getting the server time without refreshing the
page</h2>
<form>
<input type="button" value="Get Server Time"
onClick="getServerTime();" />
</form>
<div id="showtime" class="displaybox"></div>
</body>
</html>
XML and HTML look similar in many ways and this is because both are
Like HTML, XML uses tags to denote information but is not limited to the
types of tags that occur in HTML. Tags can be essentially anything a user
likes and are used to define the type of data present in the document.
XML: a (very) brief intro (cont.)
Here’s an example:
<library>
<book>
<title>Programming PHP</title>
<author>Rasmus Lerdorf</author>
<author>Kevin Tatroe</author>
<author>Peter MacIntyre</author>
<chapter number=“1”>Introduction to PHP</chapter>
<chapter number=“2”>Language Basics</chapter>
. . .
<pages>521</pages>
</book>
. . .
</library>
Accessing an XML document in JavaScript
To use an XML document in JavaScript, you must create an
object to hold it. This can be done in the following fashion:
Non-Microsoft browsers:
<script>
var myXMLDoc = document.implementation.createDocument(“”,””,null);
myXMLDoc.load(“mydoc.xml”);
// other code here
</script>
Accessing an XML document in JavaScript
Internet Explorer:
<script>
var myXMLDoc = new ActiveXObject(“Microsoft.XMLDOM”);
myXMLDoc.async=“false”;
myXMLDoc.load(“mydoc.xml”);
// other code here
</script>
Once we’ve created the object holding the XML document, we can then
use JavaScript methods to examine it, extract data from it, etc.
The “time” example using XML
The first change is to make a new PHP script that returns an XML
document to the browser.
<?php
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" ?>\n”;
echo “<clock><timenow>" . date('H:i:s') ."</timenow>< /clock>";
?>
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 page.
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);
}
}
}
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.
Some cautions
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 web pages that ignore this caution.)
Debug carefully and on many different browsers. Ajax uses features that
might not be present in all browsers or they may not operate in the same
fashion.
something has changed on the page, otherwise they may not notice it.
Some cautions
Ajax can possibly introduce strange behavior, like the “Back”
button on the browser doesn’t act like it did before (as with any
your page (generated by Ajax), then they will likely not show
The End
Thank you for patience!
26-4-2010 42