ptg 797 chapter 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). From the Library of WoweBook.Com ptg 798 Chapter 18 • An Introduction to Ajax (with JSON) reflecting 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 understanding of everything we have talked about in the preceding chapters because 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 From the Library of WoweBook.Com ptg 18.3 The Steps for Creating Ajax Communication 799 Ajax 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 document 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. From the Library of WoweBook.Com ptg 800 Chapter 18 • An Introduction to Ajax (with JSON) 3. 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 working 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. EXAMPLE 18.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! 3 try{ // Opera 8.0+, Firefox, Safari 4 ajaxRequest = new XMLHttpRequest(); // Create the object } From the Library of WoweBook.Com ptg 18.3 The Steps for Creating Ajax Communication 801 Properties 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 EXPLANATION 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. EXAMPLE 18.1 (CONTINUED) From the Library of WoweBook.Com ptg 802 Chapter 18 • An Introduction to Ajax (with JSON) Table 18.1 XMLHttpRequest Properties and Event Handlers XMLHttpRequest Property Value 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 XMLHttpRequest Method What It Does 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. From the Library of WoweBook.Com ptg 18.3 The Steps for Creating Ajax Communication 803 18.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 setting, the processing 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. EXAMPLE (SAMPLE CODE) objectRequest.open("GET", "myfile.txt", true); objectRequest.open("POST", "http://localhost/hello.php?name=George"); From the Library of WoweBook.Com ptg 804 Chapter 18 • An Introduction to Ajax (with JSON) Figure 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. From the Library of WoweBook.Com ptg 18.3 The Steps for Creating Ajax Communication 805 When 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. EXAMPLE (SAMPLE CODE) ajaxRequestObject.open("GET","http://localhost/ajaxform.php?username="+ namevalue+"&userphone="+phonevalue, true); ajaxRequestObject.send(null); EXAMPLE (SAMPLE CODE) ajaxRequestObject.open("POST", "http://localhost/ajaxform.php", true); ajaxRequestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajaxRequestObject.send(username=”+namevalue+”&userphone=”+phonevalue, true); From the Library of WoweBook.Com ptg 806 Chapter 18 • An Introduction to Ajax (with JSON) 18.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. EXAMPLE (SAMPLE CODE) objectRequest.open(“GET”, “http://localhost/test.php?name=George”, true); objectRequest.send(null); EXAMPLE (SAMPLE CODE) objectRequest.open(“POST”, “http://localhost/hello.php”); objectRequest.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”); objectRequest.send(“first=Joe&last=Blow”); EXAMPLE (SAMPLE CODE) ajaxRequest.onreadystatechange = function(){ // The function will defined later } Table 18.3 The readyState property of the XMLHttpRequest Object Status Value 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 From the Library of WoweBook.Com [...]... assigned to the object’s responseXML property This property contains an XML document object, which can be examined and parsed using the DOM, in the same way we used the DOM in Chapter 15, “The W3C DOM and JavaScript. ” The following example demonstrates how to create a simple XML file and how to use Ajax to retrieve the file data and use the DOM to access the information (see Figure 18.5) EXAMPLE (S A M... response headers define various characteristics of the data that has been requested, providing information such as the server type, the last date when the page was modified, the Content-type, and so forth JavaScript can retrieve this HTTP header information with two methods, the getAllResponseHeaders() method and the getResponseHeader() method The getAllResponseHeaders() method returns a complete list of... now causes the browser to check to see if the data has changed since that date and send a new request As long as the date is a past date, it doesn’t matter what date you use If these headers fail on a particular browser, use the random number or date options shown above EXAMPLE (S A M P L E C O D E ) ajaxRequest.setRequestHeader('If-Modified-Since', 'Sat, 03 Jan 2010 00:00:00GMT'); ajaxRequest.setRequestHeader("Cache-Control",... All of the programs go through the following steps: 1 The user clicks a button or presses a key to initiate a function that will start the process of Ajax communicating with the server 2 Most important, JavaScript uses the XMLHttpRequest constructor method to create a new object that will serve as the Ajax communication layer between the browser and the server (If not this, IFrames or cookies can be used,... response to the browser in either XML or text format It contains the data only of the page elements that need to be changed In most cases this data will include of just a fraction of the total page markup 6 JavaScript processes the server response, updates the relevant page content, or performs another operation with the new data received from the server Connecting to a Server Program If you are ready 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. ptg 797 chapter 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. 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