Hour 15. Accessing Server-Side Data via AJAX


What You’ll Learn in This Hour:

Image Using AJAX requests to load data into page elements

Image Sending AJAX GET and POST requests

Image How to serialize parameters for GET and POST requests

Image How to handle JSON and XML data in the web server AJAX response

Image Implementing AJAX event handlers to handle completion, success, and failure events


In this hour, you explore the world of asynchronous communication with the server using AJAX requests in jQuery and JavaScript. AJAX communications are one of the most vital parts of most websites. They allow jQuery and JavaScript to get additional data from the server and update the page instead of reloading or loading a new web page.

The following sections try to demystify AJAX a bit for you and they provide you with some practical examples. By the end of this hour, you will be able to implement AJAX in a variety of ways.

Making AJAX Easy

Despite its importance, AJAX tends to be a bit daunting at first. With all the communication terms, it might seem easy to get confused. That really shouldn’t be the case. If you take a quick step back to look at the basics of AJAX from a high level, the details shouldn’t seem daunting at all.

AJAX is a request from jQuery or JavaScript to the web server. The request may send data to the server, and the server will respond with a success or failure and possibly additional data. That is it—nothing more, nothing less. The following sections help clarify the request/response process.

Clarifying AJAX Versus Page Requests

The first step is to define the difference between AJAX and normal page linking request. You are already familiar with page links; when you click a link, a new web page appears. Often that is the case even if all the controls, tables, graphics, and so on are the same, but only some data has changed. In the case of form submission, none of the data changes, but the web page must still be reloaded from the server.


Caution

Don’t confuse server-side dynamic creation of web pages with AJAX. Dynamic creation of web pages is still the old traditional method—it is just a bit easier to manage. Each request back to the server still requires a full new web page to be returned. The only advantage is that the web page is generated in memory instead of read from disk.


AJAX is completely different. An AJAX request does not request a new web page from the server. Instead, an AJAX request only sends and receives bits of data necessary. If the new data received from the web server requires the web page to be updated, then jQuery and JavaScript can update the page elements, as you have already seen.

The following is a list of a few of the benefits of AJAX requests:

Image Less data requested from the web server.

Image Allows the user to continue using the web page even while the request is being processed.

Image Errors can be caught and handled on the client side before a request is ever made to the server.

Figure 15.1 illustrates the difference between the two methods of updating data in the browser.

Image

FIGURE 15.1 Comparison of AJAX requests versus traditional page linking.

Understanding Server-Side Services Such as ASP, PHP, MySQL

The next step is to understand how the AJAX requests are handled. Great detail is not necessarily important. What you need to understand is that for each AJAX request you send to a web server, a process will read the request, do some work, and then send back a response.

The back-end processes can be the web server returning a static HTML, text, XML, or JSON file. The back-end process often is an ASP, JSP, PHP, Python, or CGI script that is running on the server reading data from memory, files, databases, and other sources. The back-end process can also be a myriad of other frameworks that are integrated into the web server.

None of that really matters to the AJAX script running in the browser. All that matters is that the server sends back a status and data.

Understanding Asynchronous Communication

You need to be clear on asynchronous communication. When you request a web page from the web server, the communication is synchronous to your browser. That means the browser waits until the HTML document is downloaded from the server before it begins rendering it and retrieving the additional resources necessary.


Tip

You can do synchronous AJAX requests with both jQuery and JavaScript. The jQuery .ajax() method and the JavaScript send() function both have a Boolean field that allows this. You shouldn’t use this, though, because you can cause the browser to lock up, which will create some very unhappy users. In fact, in jQuery 1.8 and later, that option is deprecated.


AJAX communication is different when you send an AJAX request. Control is returned immediately back to jQuery or JavaScript, which can do additional things. Only when the request has completed or timed out will events be triggered in the browser that allow you to handle the request data.

Understanding Cross-Domain Requests

Cross-domain requests occur when you send AJAX requests to separate servers from different domains. The browser prevents this, and correctly so because of a multitude of security reasons.

The only problem with blocking cross-domain requests is that you often want to get data from services external to the current website. You can get around this in a couple of ways.

The first method to overcome the cross-domain restriction is to have the web server act as a proxy to the other servers or services, meaning that instead of directly communicating via JavaScript, you send the request to the server and have the server do it for you. The only downside is that it requires additional server-side scripting, and you pay an extra time penalty because data has to first be downloaded to the web server and then to the web browser.

Another option is to do what is called on-demand JavaScript, which is used by JSONP (JSON with Padding). This method takes advantage of the fact that you can download a script from another website as a resource using the following syntax:

<script type="text/javascript"
        src="http://new.domain.com/getData?jsonp=parseData">
</script>

The trick is that the address specified by the src attribute cannot return the JSON response directly. If the browser detects that the data in the script is JSON, as shown next, it throws a cross-domain error:

{ "title": "photoA", "rating": 7 };

Instead, the third-party service must support JSONP, in which case it pads the response with the function call specified by the request, as shown next. In that way, you will be able to access the data from JavaScript by calling the function.

parseData({ "title": "photoA", "rating": 7 });

Looking at GET Versus POST Requests

This section clarifies GET and POST requests. The two main types of requests that you send to the web server are GET and POST. There are only a few differences between the two, but they are important. A GET request passes parameters as part of the URL, whereas a POST request passes them as part of the request data.

To help you quickly see this, the following illustrates the basic URL and data involved to send a first and last name to the server in a GET and POST request:

GET request URL:

http://localhost/code/example1.html?first=Brad&last=Dayley

GET request data:

<empty>

POST request URL:

http://localhost/code/example1.html

POST request data:

first=Brad
last=Dayley

Which request type should you use? The basic rule is to use a GET for retrieving information from the server and a POST if you are changing data on the server.

Understanding Response Data Types—Binary Versus Text Versus XML Versus JSON

It’s important to be clear on the response data types that may come back from the server. The data that comes back to an AJAX request will be either in some sort of binary or text format. Typically, binary is reserved for images, zip files, and the like. However, text may be raw text, HTML, XML, JSON, and so on.

What does that mean? This is where it can get a bit tricky. When the browser receives a response from the server, it attempts to determine the type of data received by the server and create the appropriate response object for you to use.

For XML and HTML data, a DOM object is created, whereas for JSON, a JavaScript object is created. For raw text or binary objects, an object is constructed that provides access to the raw text or binary data.

Implementing AJAX

Now that you have your head wrapped around the AJAX concepts, you are ready to begin implementing the basic details. To implement AJAX requests, you need to access the HTTP request object, format the data that needs to be sent to the server, send the request, and then handle the response.

Both JavaScript and jQuery have methods to send an AJAX request to the web server. You’ll see both methods in the following sections. jQuery is able to do everything that JavaScript can do, but in a much easier and extensible manner.

The following sections discuss and provide some examples of implementing basic AJAX requests.

AJAX from JavaScript

To implement an AJAX request in JavaScript, you need access to a new window.XMLHttpRequest object. Table 15.1 describes the important methods and attributes of the XMLHttpRequest object:

Image

TABLE 15.1 Important Methods and Attributes of the XMLHttpRequest Object

To illustrate this, check out the following code that sends a GET AJAX request to the server to get the email address based on first and last name parameters:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    { document.getElementById("email").innerHTML=xmlhttp.responseText;}
  }
xmlhttp.open("GET","getUserEmail.php?userid=brad",true);
xmlhttp.send();

The following code illustrates how to send a basic POST AJAX request to the server to set the email address. Notice that for the POST request, the added Content-length and Content-type headers make sure that the data is treated correctly at the server. The Content-length is set to the length of the params string.

var xmlhttp = new XMLHttpRequest();
var params = "first=Brad&last=Dayley&[email protected]";
http.setRequestHeader("Content-type", "text/plain");
http.setRequestHeader("Content-length", params.length);
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    { alert("Email Updated");
  }
xmlhttp.open("POST","setUserEmail.php",true);
xmlhttp.send(params);


Note

In Internet Explorer browsers earlier than IE7, you need to use the following line to create the xmlhttp object because the window object doesn’t support the XMLHttpRequest attribute:

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");


AJAX from jQuery

This section looks at implementing AJAX requests from jQuery. jQuery provides very simple-to-use wrapper methods to implement AJAX requests, .load(), .get(), and .post().

The helper functions are wrappers around the .ajax() interface, which is discussed later. These helper functions are the following:

Image .load(url [, data ] [, success(data, textStatus, jqXHR) ] )—This method is used to load data directly into elements represented by the jQuery object.

Image .getScript (url [, data ] [, success(data, textStatus, jqXHR) ] ) )—This method is used to load and then immediately execute a JavaScript/jQuery script.

Image .getJSON(url [, data ] [, success(data, textStatus, jqXHR) ] ) )—This method is used to load data in JSON format using a JSONP request to servers on different domains.

Image .get(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ]) )—This method is used to send a generic GET request to the server.

Image .post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ]) )—This method is used to send a generic POST request to the server.

Each of these methods enables you to specify the url of the request. The .load() method is used to load data directly into elements represented by jQuery object. The .get() and .post() methods are used to send GET and POST requests.

The data argument can be a string or basic JavaScript object. For example, in the following example, obj, objString, and formString are all valid data arguments:

var obj ={"first":"Brad", "last":"Dayley"};
var objString = $.param(obj);
var formString = $("form").serialize();

You can also specify the function that executes when the response from the server succeeds. For example, the following success handler sets the value of the #email element to the value response data:

$.get("getEmail.php?first=Brad&last=Dayley", null, function (data, status, xObj){
  $("#email").html(data);
}));

The .get() and .post() methods also enable you to specify a dataType parameter as a string, such as “xml", "json", "script", "html", and so on, that formats the expected format of the response data from the server. For example, to specify a response type of JSON, you would use the following:

$.get("getUser.php?first=Brad&last=Dayley", null, function (data, status, xObj){
  $("#email").html(data.email);
}), "json");

Handling AJAX Responses

In addition to specifying the success handler, the wrapper methods also enable you to attach additional handlers using the following methods:

Image .done(data, textStatus, jqXHR)—Called when a successful response is received from the server.

Image .fail(data, textStatus, jqXHR)—Called when a failure response is received from the server or the request times out.

Image .always(data, textStatus, jqXHR)—Always called when a response is received from the server.

For example, the following code adds an event handler that is called when the request fails:

$.get("getUser.php?first=Brad&last=Dayley", null, function (data, status, xObj){
  $("#email").html(data.email);
}), "json").fail(function(data, status, xObj){
  alert("Request Failed");
});

Handling Response Data

You have already learned about the different data types that can be generated by the response. The four main types that you will be working with are script, text, JSON, and XML/HTML. The script and text are handled simply by the .load() and .getScript() methods. JSON and XML/HTML can be a bit more complex.

The following sections walk you through the process of handling JSON and XML data in the response from the server.

Using Advanced jQuery AJAX

The concepts already covered in this hour should take care of most of your AJAX needs. However, they do not cover the full power of the jQuery AJAX interface. The following sections discuss some of the additional AJAX functionality built directly into jQuery.

Reviewing Global Setup

jQuery provides the .ajaxSetup() method that allows you to specify options that configure AJAX requests globally throughout the script. Table 15.3 lists some of the options that can be specified when calling .ajaxSetup(). For example, the following code sets the default global URL for requests:

$.ajaxSetup({url:"service.php", accepts:"json"})

Using Global Event Handlers

jQuery provides methods to create global event handlers that are called on events, such as initialization or completion for all AJAX requests. The global events are fired on each AJAX request. Table 15.2 lists the methods that you can use to register global event handlers.

Image

TABLE 15.2 jQuery Global AJAX Event Handler Registration Methods

An example of using global event handlers to set the class of a form is shown next:

$(document).ajaxStart(function(){
  $("form").addClass("processing");
});
$(document).ajaxComplete(function(){
  $("form").removeClass("processing");
});


Note

Global events are never fired for cross-domain script or JSONP requests, regardless of the value of the global property in jQuery.ajaxSetup().


Implementing Low-Level AJAX Requests

All AJAX request wrapper methods that you have been working with in this hour are handled underneath through the .ajax(url [, settings]) interface. This interface is a bit more difficult to use, but it gives you much more flexibility and control of the AJAX request.

The .ajax() method is called the same way that .get() and .post() are; however, the settings argument allows you to set a variety of settings used when making the request.

Table 15.3 lists the more common settings that can be applied to the .ajax() method.

Image

TABLE 15.3 Common Settings Available in the .ajax() Request Method

A simple example of using the .ajax() interface is shown in the following code:

$.ajax({
  url:"setEmail",
  type:"get",
  accepts:"json",
  contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
  data: {"first":"Brad", "last":"Dayley"}
}).fail(function(){ alert("request Failed"); });

The .ajax() method returns a jqXHR method that provides some additional functionality, especially when handling the response. Table 15.4 lists some of the methods and attributes attached to the jqXHR object.

Image

TABLE 15.4 Common Methods and Attributes of the jqXHR Object Returned by .ajax()

Summary

AJAX is the basic communication framework between jQuery/JavaScript and the web server. Using AJAX allows you to get additional data from the web server and use it to dynamically update the web page instead of completely reloading it. This enables you to provide a much better experience for the user.

In this hour, you learned the ins and outs of AJAX. You were able to implement several examples that gave you experience with GET and POST requests, as well as handling different types of data, such as HTML, JSON, and XML.

Q&A

Q. Why is there a GET and a POST request and not just one request?

A. The answer is optimization. Although you could do everything with just POST requests, optimizations can be made at the web server as well as the browser by using GET requests that have the parameters directly in the URL. This is especially true with caching.

Q. Are there any other methods to send cross-domain requests besides JSONP?

A. Yes. Flash and Silverlight both have mechanisms that allow you to send cross-domain requests. HTML5 also introduces the postMessage interface designed to allow cross-domain requests.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try to answer the questions before looking at the answers.

Quiz

1. Would you use a GET or a POST request to set a new password on a web server?

2. True or False: The .done() event handler function is called only if the AJAX request succeeds.

3. What data type is the response data converted to for XML data?

4. What data type is the response data converted to for JSON data?

5. Is it possible to specify the request headers sent with a GET request via jQuery?

Quiz Answers

1. POST.

2. True.

3. DOM object.

4. Basic JavaScript object.

5. Yes. You can use .ajax() with the headers parameter, or you can use .ajaxSetup() to set the headers parameter globally.

Exercises

1. Modify the example in Listing 15.3. Add an additional date value to each image in the JSON file. Then add the date value along with the image on the web page by including it in the image caption.

2. Modify the example in Listing 15.4. Add an additional column for rating. You will need to update the XML file, as well as the AJAX response handlers, to add the additional column to the rows. Also, you will need to fix up the CSS.

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

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