In this approach, asynchronous means that when a request is initiated by the occurrence of a client event, JavaScript functions using Ajax allow the browser to interact in the background
Trang 1797
18
An Introduction to
Ajax (with JSON)
18.1 Why Ajax?
JavaScript has gone through kind of a Renaissance of its own since this book was first
published in 2002 largely due to the hype and promises it offers Traditionally Web
applications have been somewhat clumsy and slow, and the level of interactivity and
usability inferior to their counterpart desktop applications, yet the number of Web
applications available continues to grow at an amazing rate Part of that growth has been
spurred on by AJAX, “Asynchronous JavaScript and XML,”1 not a new programming
language, but a methodology for creating fast, rich, user-friendly, and interactive Web
applications by allowing a Web page to request small fragments of information from the
server instead of an entire page In this approach, asynchronous means that when a
request is initiated by the occurrence of a client event, JavaScript functions using Ajax
allow the browser to interact in the background directly with the server, and rather than
waiting for the server to respond, continue processing the page The server will then
send its response to Ajax containing only the data that needs changing Ajax in turn will
update that portion of the Web page For example, if you are filling out a form, instead
of waiting until all the fields have been filled and the page submitted, now with Ajax,
the fields can be validated as they are filled and the user does not have to sit by waiting
for the page to reload before continuing what he or she was doing This process is shown
in Figure 18.1
As discussed in Chapter 1, “Introduction to JavaScript,” Google offers great
exam-ples of Ajax with Google Maps and Google Suggests, an application shared now by all
major browsers (In fact, Ajax was made popular in 2005 with Google Suggest.) When
the you start searching in the Google search box, each time you press a key, Google
lists items that fit that sequence of letters In a drop-down list, as if by magic, words
appear that contain those letters, and after each subsequent key press, the list changes,
1 The term Ajax was coined in 2005 Jesse James Garrett thought of the term while in the
shower See http://en.wikipedia.org/wiki/Ajax_(programming).
Trang 2reflecting a more refined search This dynamic and immediate update of the list is an
example of Ajax in action In Figure 18.2, the letters j, a, and v have been typed in the
search box A list of words appears starting with those letters The user can select any
of the suggested items and search for that item without typing any more if he or she
sees a word that matches his or her search criteria There is no delay, no waiting with
an Ajax application
18.2 Why Is Ajax Covered Last?
Why is Ajax the last chapter in this book? If you browse around the Internet for books
or tutorials on Ajax, you will soon realize that Ajax requires that you have some basic
Figure 18.1 The request/response loop with and without Ajax.
Server Browser HTTP request
response
Non-Ajax Way
User requests a page via URL
Server gets the page, sends it to the browser
Server Browser HTTP request
User fills out a form and
submits it, then waits
Server works, validates form,
open database, etc.
Server Browser
response Page is reloaded,
user continues
Server Browser HTTP request
response
Ajax Way
User requests a page
Server sends back page
Server Communication
layer Browser
Communication layer
User starts filling out form, triggers
an event by changing a value
or moving a key
Server Browser
Page not reloaded, user not interrupted
Ajax updates Web page in increments
Ajax makes incremental function calls to the server in the background
Trang 3Ajax is based on already existing standards If you have a strong foundation in the
fol-lowing topics, there is very little new to learn:
• JavaScript
• XML
• HTML
• CSS
• DOM
We have not covered XML in this book, but it has been a standard format since 1998
for sharing structured text-based information between computers XML is not a
require-ment for writing Ajax applications, but we will examine an XML docurequire-ment and how
Ajax processes its data
18.3 The Steps for Creating Ajax
Communication
We will now go through the steps to create and send requests to the server We examine
each of these steps and then put all of them together in several examples
1 First and foremost we must create an XMLHttpRequest object, a JavaScript
object with properties and methods used to handle communication between the browser and server
2 After we create the request object, we use the object’s open() method to
initial-ize the object; that is, tell it how the data will be sent, GET or POST (see Chapter 11, “Working with Forms and Input Devices”), and the URL of the file data that is being requested The URL could be a text file, XML data, or a server-side program such as PHP, ASP.NET, CGI, Java Servlet, and so on
Figure 18.2 Google Suggests © 2010 Google.
Trang 43 The request is sent to the server with the send() method
4 After the request is sent to the server, the object’s readyState property keeps
track of the state of the request object; for example, if a request has been made, the state changes With an event handler, a callback function can be executed based on the state of the object If, for example, the request has been answered and all the information has been sent by the server, the state of the object can be checked and a function called to retrieve and handle the data
Now we will take a closer look at each of the steps to create Ajax communication
between the browser and the server
18.3.1 Step 1: Create the XMLHttpRequest Object
With the HTTP request/response cycle we discussed at the beginning of the book, when
the user clicks a link, submits a form, or types an address in the URL, an HTTP
connec-tion is made between the browser and the server The server’s response is to send back
a new or updated page while the user waits With applications that make asynchronous
calls to the server, there has to be a way to do this without refreshing the page for each
HTTP request This is done with the XMLHttpRequest object This object allows
Java-Script to set up a communication channel with the server, exchange data, and update
the page without reloading it Meanwhile the user continues scrolling, typing, and
push-ing buttons just as he or she would on a desktop application, while Ajax is workpush-ing with
the server in the background
The XMLHttpRequest object is supported by all major browsers (Firefox, Chrome,
Opera, and Safari) and is fundamental to all Ajax applications Internet Explorer 7 comes
with the XMLHttpRequest, but other versions of Internet Explorer support the ActiveX
object, which is not cross-browser compliant Therefore, when creating a new
XMLHttpRe-quest object, most JavaScript programs use catch and try statements to make sure the object
they get back is compatible with their browser (See Chapter 7, “Functions,” for a review
of catch and try.) Example 18.1 demonstrates how to create the XMLHttpRequest object for
most major browsers See https://developer.mozilla.org/en/AJAX/Getting_Started.
E X A M P L E 1 8 1
/* Check browser type and create ajaxRequest object
Put this function in an external js file and use it for your Ajax programs */
1 function CreateRequestObject(){
2 var ajaxRequest; // The variable that makes Ajax possible!
// Opera 8.0+, Firefox, Safari
4 ajaxRequest = new XMLHttpRequest(); // Create the object
}
Trang 5Properties and Methods. The XMLHttpRequest object has several important
prop-erties and methods that will give you information about the status of the request
response, the data that was returned from the server, when the state of the server
changes, and so on There are methods to initialize the XMLHttpRequest object, send a
request, inform you about what is in the response headers, how to cancel a request, and
so on You will see the properties and methods in Tables 18.1 and 18.2 used in the Ajax
examples that follow
catch (e){
// Internet Explorer Browsers try{
5 ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
} } }
6 return ajaxRequest;
} //End function
E X P L A N A T I O N
1 The CreateRequestObject function creates the XMLHttpRequest object for Ajax to
set up communication between JavaScript and the server
2 This variable will be used to hold a reference to a new Ajax XMLHttpRequest object
created in this function
3 If the try block has no errors, its statements will be executed; otherwise, the catch
block will be executed
4 For most modern browsers, this try will succeed Here the XMLHttpRequest()
method will create a new object called ajaxRequest (The object name is named
any valid variable name.)
5 The catch blocks are executed if the browser is Microsoft Internet Explorer
Inter-net Explorer uses the ActiveXObject() method to create the Ajax object rather than
the XMLHttpRequest() method.
6 If successful, an Ajax request object will be returned from this function
E X A M P L E 1 8 1 (C O N T I N U E D)
Trang 6Table 18.1 XMLHttpRequest Properties and Event Handlers
status The HTTP status code of the request response; for example,
200 or 404.
statusText Returns the HTTP status code from server response as a
string us as OK or Not Found.
readyState A number representing the current state of the object (see
Table 18.3).
responseText Returns a string value of unparsed text as a response from
the server.
responseXML Returns response parsed into a DOM if Content-type is
text/xml Used to get multiple values.
onreadystatechange The event handler that is called when the readyState
changes.
onerror Mozilla event handler that is called when an error happens
during a request.
onprogress Mozilla event handler called as content is loaded.
onload Mozilla event handler called when the document is finished
loading.
Table 18.2 XMLHttpRequest Methods
abort() Cancels the request
getAllResponseHeaders() Returns a string of all the HTTP headers separated by a
newline
getResponseHeader(“server”) Returns the value of a specific HTTP header; for example,
“Server” or “Last-Modified”.
open() Initializes the XMLHttpRequest object with GET or POST,
URL, and so on.
send() Sends the request.
setRequestHeader() Adds a key/value pair to add to the header that will be sent
to the server.
Trang 718.3.2 Step 2: Initializing the Object
Whether retrieving a simple text file, XML file, sending form data, or retrieving
infor-mation from a database, a request will ask for a resource from the server To get this
information the request object needs to know how the request will be submitted (i.e.,
GET or POST; use capital letters) and the URL defining the location of the file or
server-side script (When creating HTML forms, this information was normally stored in the
ACTION and METHOD attributes of the <form> tag.) Once the object has this
informa-tion, the request can be made
The open() Method. The open() method prepares or initializes the object for
com-munication with the server, whereas the send() method actually makes the request The
open() method takes three arguments:
1 The request type; that is, how the data is submitted, either GET or POST.2
2 The URL of the file or server-side program and parameters representing the data
being sent as key/value pairs
3 An optional third parameter of Boolean true (asynchronous) or false
(synchro-nous) When set to true, the default, the processing will continue without wait-ing for the server to respond, whereas with a false settwait-ing, the processwait-ing will
stop until the server responds
Except for simple file retrieval or searches, the POST method is used, but this requires
an additional request header method, and the data represented as name/value pairs is
sent to the server as an argument to the send() method.
It is important to note that for security reasons, the URL must be within the same
domain as the request object; for example, JavaScript is not permitted to open an
XML-HttpRequest to any server other than the same Web server currently being visited by the
user
GET or POST. The way data is sent to a server with the HTTP protocol depends on
whether the method being used is GET or POST (To review these two methods, go to
Chapter 11, section “About HTML Forms” on page 334.) In either case, the data being
sent is in a URL-encoded query string consisting of name/value pairs With the GET
method, the browser sends data in the URL (see Figure 18.3), whereas with the POST
method it sends additional data to the server specified in headers, a blank line, and
finally the data (see Figure 18.4) Ajax handles GET and POST differently as well
2 You can also use the HEAD request method.
E X A M P L E ( SA M P L E CO D E)
objectRequest.open("GET", "myfile.txt", true);
objectRequest.open("POST", "http://localhost/hello.php?name=George");
Trang 8Figure 18.3 Firefox Live Headers shows how the GET method sends data in a query string
appended to a the URL and a question mark (shown in highlighted bar).
Figure 18.4 Firefox Live Headers add-on shows POST data sent as part of the HTTP header.
Trang 9When the first parameter to the Ajax open() method is GET, the second argument is
the URL of the page that is being requested If the URL is a server-side script, such as
PHP or ASP.NET, any input data (name/value pairs), is sent as a URL-encoded query
string A question mark, followed by the query string, is appended to the URL As you
might remember in traditional form processing, if the GET method is used, the data will
be attached to the URL in the location box of the browser, visible to all With Ajax the
URL is an argument to the open() method and is not visible in the browser window
because it is being sent directly from Ajax to the server For the GET method:
With the POST method, additional data is sent to the server The first argument to
the open() method will be POST, the second argument, the URL of the server script, and
the third true for asynchronous Instead of attaching the query string to the URL it will
be sent as an argument to the send() method.
The setRequestHeader() method is added to specify the Content-type, set to
“appli-cation/x-www-form-urlencoded” This is needed for any POST request made via Ajax
Finally, the send() method is called, passing in the parameters that will be sent to the
server-side program (without the “?” prefix) This data is formatted as a query string
(e.g., “name=value&foo=bar”), and not visible in the browser
18.3.3 Sending the Request to the Server
Once the object has been initialized, the browser can send a request to the server with
the send() method This method takes one argument of “null” if you use the GET
method for sending the data As discussed in the previous section, with the POST
method, an additional step is required The setRequestHeader() method tells the server
the “Content-type”, and the send() method sends the query string as name/value pairs
to the server
E X A M P L E ( SA M P L E CO D E)
ajaxRequestObject.open("GET","http://localhost/ajaxform.php?username="+
namevalue+"&userphone="+phonevalue, true);
ajaxRequestObject.send(null);
E X A M P L E ( SA M P L E CO D E)
ajaxRequestObject.open("POST", "http://localhost/ajaxform.php", true);
ajaxRequestObject.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
ajaxRequestObject.send(username=”+namevalue+”&userphone=”+phonevalue,
true);
Trang 1018.3.4 Step 3: Monitoring the State of the Server Response
Monitoring the State of the Server. After sending a request to the server, we need
to know when the request has completed and what to do with the information when it
comes back The onreadystatechange event handler of the XMLHttpRequest object is
assigned a function that will be called automatically when the onreadystatechange event
handler is triggered; that is, when the state of the server changes
What does readyState mean? The XMLHttpRequest object keeps track of the status of
the server’s response in another property called readyState This property has one of the
values shown in Table 18.3
E X A M P L E ( SA M P L E CO D E)
objectRequest.open(“GET”, “http://localhost/test.php?name=George”, true);
objectRequest.send(null);
E X A M P L E ( SA M P L E CO D E)
objectRequest.open(“POST”, “http://localhost/hello.php”);
objectRequest.setRequestHeader(“Content-Type”,
“application/x-www-form-urlencoded”);
objectRequest.send(“first=Joe&last=Blow”);
E X A M P L E ( SA M P L E CO D E)
ajaxRequest.onreadystatechange = function(){
// The function will defined later
}
Table 18.3 The readyState property of the XMLHttpRequest Object
0 Object, has been created, not initialized
1 Loading, send method not yet called
2 Loaded, send method called, headers not available
3 Interactive, some data has been received, status and response headers not
available
4 Complete, all data has been received and is available