Appendix B. Review of the XMLHttpRequest API

This appendix covers

  • A review of the XMLHttpRequest API
  • The building of an XHR data source module

In this appendix, you’ll review the low-level API for making a server call. In a real-world application, you’ll likely rely on your MV* framework for XHR calls if it has this capability built in or a helper library such as jQuery if it doesn’t. These frameworks and libraries often abstract away much of the boilerplate code and provide you with simple, easy-to-use methods instead. Even so, it’s good to have at least a general idea of what’s going on under the covers. That’s why I’ll stick with vanilla JavaScript here, so you can see basic XHR mechanics at work. I’ll also not be using RESTful calls here, just to keep things fairly straightforward.

B.1. Using the XMLHttpRequest object

When you hear someone talk about making an AJAX call, they’re usually talking about making an XHR call (XHR is short for XMLHttpRequest). AJAX (or Ajax) is short for Asynchronous JavaScript and XML and generally refers to using JavaScript to dynamically update a web page with the results of an XHR call. This section focuses solely on the XMLHttpRequest part of AJAX.

As I mentioned in chapter 1, the XMLHttpRequest functionality was originally created by developers at Microsoft. Eventually, it became a standard API with implementations in all the major browsers. This standard allows you to create an instance of the XMLHttpRequest object by using simple JavaScript, and the object will behave similarly across most modern browsers.

You start by creating an instance of the object. As long as the user is using a browser that supports the API, this one line of code is all you need to create the object:

var xhrObj = new XMLHttpRequest();

If you need to support Microsoft Internet Explorer prior to version 7, you should wrap your object’s creation in a check for the XMLHttpRequest object and use an ActiveX object if the XMLHttpRequest object is not available. Microsoft recommends this approach:

function createXHRObject() {
   if (window.XMLHttpRequest) {
      return new XMLHttpRequest();
   }
   else {
      return new ActiveXObject("Microsoft.XMLHTTP");
   }
}

With an instance of the object created, you can now make an asynchronous request to your server.

B.2. Making requests

After you’ve created an instance of the XHR object, you can use its events, methods, and properties to customize your server call. The following is a list of the XHR concepts demonstrated in this section:

  • onreadystatechange —This event fires when the state of the call changes. You assign your own function to handle this event. The most common use of this event is to see whether the call has completed. If so, you can subsequently check whether it succeeded or failed and react accordingly.
  • open —This method assigns the request method and URL for the call. Many request methods exist, but not all of them may be supported by the technology you’re using on the server. In chapter 7, we’re using only GET, POST, PUT, and DELETE.
  • setRequestHeader —With this method, you can specify the request headers for the request, such as the type of content you’re sending and the type of content you’ll accept in the response.
  • send —This method fires the request. For requests that don’t need a body, such as a GET request, you can pass in null or use the overloaded version of this function that takes no parameters (this is the preferred approach). Otherwise, you use this method’s parameter to pass data for the request body.
  • readyState —This is the property you’ll check when the onreadystate event fires to let you know what state the call is in. The readyState property has five basic values: 0 (UNSENT), 1 (OPENED), 2 (HEADERS_RECEIVED), 3 (LOADING), and 4 (DONE). For most situations, you’ll need only to check for a value of 4 to make sure the call has finished.
  • status —You’ll check this property when the call completes to see whether it succeeded or failed. Status codes in the 400s and 500s represent errors. You can find a complete list of the status codes at www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  • responseText —This property contains the response body as a string. For JSON calls with no errors, the JSON text will be found here. In an error situation, it’s up to the creators of the server-side code to determine what’s written in the response body.
  • responseXML —This property contains a Document object if the response can be parsed as XML or HTML. Otherwise, this property is null.

I’m covering only the basics here, but a full listing of the XMLHttpRequest API can be found at www.w3.org/TR/XMLHttpRequest.

B.2.1. Using URL parameters

When retrieving information using a request with a simple payload or no payload at all, the GET method is a good choice. In this type of request, no body is sent. Instead, URL parameters are appended to the URL itself when information needs to be sent. In our first example (see listing B.1), you’ll use a simple GET request with a single URL parameter (the ID of the shopping cart) to retrieve the contents of a shopping cart.

In the shopping cart application for chapter 7, you use AngularJS to bind the data returned to the view. Here, you write things out to the console to get a better understanding of what’s going on with each request.

Listing B.1. XHR call using GET and URL parameters

After the request completes, the following information prints to the console:

Success:
readyState: 4
status: 200
statusText: OK

The readyState is 4 for complete, and the status of your call is 200/OK. You can also look at the Network tab in the developer tools of your browser to confirm the request URL and the request headers (see figure B.1).

Figure B.1. Your request to get the shopping cart contents is successful. You use a GET request, passing a cart ID of 123 via a URL parameter.

While you’re in the developer tools of the browser, you can also see the server’s output in the console (see figure B.2).

Figure B.2. The server responds with your shopping cart’s JSON-formatted text. You can see that the cart has no items.

Looking at the response in the Network tab, you can see that you don’t have any items in your cart.

To add a game to the shopping cart, you need only the cart ID and the ID of the game. You could continue to use URL parameters, but sending a more complex request payload might be a better choice. To send a more complex payload, you’ll need to rely on the request body.

B.2.2. Using the request body

When you add a new item to your shopping cart, you’d like to send an object in the request. For this request, you’ll convert your JavaScript request object into a JSON string and pass that via the request body. The following listing illustrates this technique.

Listing B.2. XHR call using POST and the request body

Note

JSON.js can be used as a polyfill for the JSON object if older browsers must be supported.

Looking at the code, you’ll see that this time you’re using POST for your request method so you can use the request body. You’re then using the JavaScript method JSON.stringify() to transform your JavaScript object into JSON-formatted text. Next, you pass the text into the send() method of your XHR object so the payload is sent in the body of the request.

Another thing to note is that this time, because you’re sending JSON, you need to specify that as another request header. Let’s see what the request looks like now in your Network tab (see figure B.3).

Figure B.3. You use the POST method to send complex request objects in the form of JSON-formatted text to the server from your SPA.

On the server, the code is written so that the entire cart is returned each time an addition or update is made. Checking the returned JSON, you can see that you have the item with the ID madden_nfl_15 in the cart (see figure B.4).

Figure B.4. After the new item is posted to the server, you have one game in your shopping cart.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset