References Used
- Javascript in 24 Hours by Michael Moncur. Sams Publishing, 2007.
AJAX Essentials
- AJAX = Asynchronous JavaScript and XML
- AJax allows Javascript to communicate asynchronously with a server and
to update a web page without having to reload it. Traditional Javascript
applications work as follows:
- The Javascript application posts a form to the web server
- The web server calculates the results and creates a completely
new web page from scratch. Even if the web page differs only slightly
from the original web page, the entire web page must be re-created.
- The web server sends the new page back to the browser. Any
pre-existing Javascript state is lost because the state is lost
as soon as the original page is sent to the server.
The roundtrip that is involved with this process can make the server
appear sluggish. It can also be tedious for the server to have to try
to remember all the form data that was entered by the user. In fact you
have probably noticed that many web sites simply forget the data that
you entered and make you re-enter it, something I find incredibly annoying.
With Ajax Javascript is able to send a request to the server without
submitting the entire form. The user is able to continue working with
the form while the server processes the result. When the server is done
it sends the result back to Javascript and Javascript can appropriately
update the form, without having to re-load the entire page. Because the
requests are asynchronous, Javascript can have multiple requests outstanding
at any given time.
- Sample Ajax Applications
- Email: An email handler can be written with a client side in Javascript
and a server side written in PhP. The Javascript side can handle the
syntactic, form-based aspects of displaying email messages in a list.
It can incrementally remove mail items from the list, add them to
the list in response to queries to the server, display email messages,
etc. Each request--delete, fetch new mail, display mail message--can
be handled with requests to the server followed by updating the
email form presented to the user.
- Incremental search: An increasingly popular feature on web-sites
is incremental search, whereby search results are refined with each
keypress by a user. On each keypress a request is sent to the server
and the server refines the search results based on the text string
entered thus far by the user. The server sends back the results to
Javascript which then updates the form with the refined set.
- Polling: Many web-sites, such as American Idol or news sites, allow
users to respond to poll questions without having to reload the
entire page. This is done by sending a request to the server to update
the vote tallies when the user presses an appropriate radio button.
- Stock quotes: Financial web-sites continuously update stock quotes
by using Ajax requests to query a server-side database for price
information and then updating the information on the client-side.
- Steps in using Ajax
- Script makes a request to the server--user can still operate
browser, such as typing text into a text field or clicking
a button
- Server-side script processes request and puts information into
either an XML object or a text string
- XML object/text string gets sent back to Javascript and a notification
event is triggered
- Javascript function that handles the notification event
processes the XML object using DOM manipulation functions
and displays the result
- Safari, Firefox, IE7 share a common AJAX interface.
IE5 and IE6 have a slightly different AJAX interface that uses ActiveX
controls.
Operations with Each Ajax Step
An Ajax Request Library
The process of launching an Ajax request and then processing the response
can be tedious, so I have prepared an Ajax library
that you can use. The library contains two functions:
- ajaxRequest(send_type, url, params, callback): creates and
returns an ajax object (i.e., an XMLHttpRequest object). This is the
function you will call to create an ajax object. The
four parameters are as follows:
- send_type: either "GET" or "POST"
- url: the url of the script or the url of the XML file you want to open
- params: a string of the form "name1=value1&name2=value2&...&namen=valuen" or "" if there are no parameters.
- callback: a pointer to the callback function. The callback function
will be made a method of the ajax object so if you want to access
properties of the ajax object, you should use the this
keyword to access its properties.
The callback function takes no arguments but you can get around this
restriction by adding additional properties to the ajax object. Since
the callback function is made a method of the ajax object, it will be
able to access these properties by prefixing the properties with the
this keyword.
- ajaxResponse(): This is an internal function that you should never
call. The ajaxRequest function makes ajaxResponse be the
function that gets called by the onreadystatechange event.
ajaxRequest ensures that your callback function gets called when
the server has completed its processing of your request.
ajaxRequest makes ajaxResponse be a method of the ajax request
object so that ajaxResponse handles the correct ajax call. Since
the onreadystatechange event does not pass any parameters to the
function it calls, it is necessary to make the ajaxResponse function
be a method of your ajax object, so that it can access the appropriate
callback function.
If you use this library, you can have easily have multiple Ajax requests
pending simultaneously, and ensure that the correct callback function gets
invoked for each one
(e.g., for different quotes on a financial web site).
Changing HTML Content on the Client Side
Frequently an ajax response will need to change the content of html elements.
This can be accomplished by retrieving the appropriate element using a DOM
query command and then modifying its innerHTML property.
To retrieve the element, you should use getElementById
if the html element is identified with an id attribute and
getElementByName if the html element is identified with an id
attribute. For example:
document.getElementById('ibm').innerHTML = 98.46; // element uses id
document.getElementByName('ibm').innerHTML = 98.46; // element uses name
If the innerHTML property does not work, you can fall back on traversing the
DOM tree. The html content is in the first node of a text element and can be
accessed via the nodeValue property:
document.getElementById(ibm').firstChild.nodeValue = 98.46
Note that if the document were an XML document rather than an html document,
you would have to use the second approach, because the innerHTML
property would not be defined for nodes in an XML document.
Server Side Issues
These notes will deal with retrieving information stored in an XML document.
You can even more easily retrieve information from an SQL database and then
output it in XML format using the techniques described in this section. There
are several issues you need to be aware of in order to make your server-side
script work in the way you anticipate:
- If you want to read an XML document then its file permission must be
set to be world readable. If you also want to be able to update the
XML document, then the file permission must be set to be both world
readable and writeable.
- You should use the DOM parser to modify the contents of an XML file. You
will need to use the createElement and replaceElement
commands to do so.
While you should be able to modify text content using the simpleXML parser,
it does not seem to work correctly in practice.
- Once you have modified your XML content, you will want to save it.
Unlike the simpleXML parser, the DOM parser does not provide a command
that both converts the XML document to a text string and writes it to
a file. Instead it only provides a command to convert the XML document
to a text string. You will need to use fopen/fputs/fclose to actually
save the document. For example:
$xmlDoc->formatOutput = true;
$handle = fopen("quotes.xml", "w");
fputs($handle, $xmlDoc->saveXML());
fclose($handle);
- If you want your PHP script's output to be treated as an XML document by
the client-side brower,
then you need to write out a header that tells the browser that the
document is an XML document. You can write out an appropriate header
using PHP's header command:
header('Content-Type: text/xml; charset=utf-8');
The important information in this header is the "text/xml" content-type,
which tells the browser to treat this document as an XML document.
If you fail to have your PHP script write out this header information, then
the ajax request object on the client-side will have its responseText
field set, but its responseXML field will be set to null.
- In addition to saving an XML document to a file, you may want to write
out the XML document to the client. If you want to send the
XML document to the client, use the document's saveXML command to
generate a text string and then
make sure you use PHP's echo or print commands to print the string returned
by the saveXML command. If you do not do so, then the string will not
be included in the XML document returned to the client. For example,
write this code:
echo $xmlDoc->saveXML();
instead of this code:
// missing echo command means that the text string returned by saveXML
// will not be inserted into the XML document returned to the client
$xmlDoc->saveXML();
Examples
- Interactive Quiz: This
interactive quiz allows you to answer a set of multiple choice questions about
Javascript and then displays your score at the end of the quiz. You can view the
page source to see what the page looks like. The support files are:
- ajax.js
- quiz.js
- questions.xml
In class we will do a more complicated example that involves being able to
vote for your favorite color and see the counts for each color be updated
in real-time. To do this we will actually have to write both client-side and
server-side scripts.