Chapter 4

Embracing AJAX and JSON

IN THIS CHAPTER

check Reading and writing JSON

check Understanding AJAX

check Using AJAX

“The Web does not just connect machines, it connects people.”

— TIM BERNERS-LEE

AJAX is a technique for making web pages more dynamic by sending and receiving data in the background while the user interacts with the pages. JSON has become the standard data format used by AJAX applications. In this chapter, you find out how to use AJAX techniques to make your site sparkle!

Working behind the Scenes with AJAX

Asynchronous JavaScript + XML (AJAX) is a term that’s used to describe a method of using JavaScript, the DOM, HTML, and the XMLHttpRequest object together to refresh parts of a web page with live data without needing to refresh the entire page.

technicalstuff AJAX was first implemented on a large scale by Google’s Gmail in 2004 and then was given its name by Jesse James Garret in 2005.

The HTML DOM changes the page dynamically. The important innovation that AJAX made was to use the XMLHttpRequest object to retrieve data from the server asynchronously (in the background) without blocking the execution of the rest of the JavaScript on the web page.

Although AJAX originally relied on data formatted as XML (hence the X in the name), it’s much more common today for AJAX applications to use a data format called JavaScript Object Notation (JSON). Most people still call applications that get JSON data asynchronously from a server AJAX, but a more technically accurate (but less memorable) acronym would be AJAJ.

AJAX examples

When web developers first started to use AJAX, it became one of the hallmarks of what was labeled Web 2.0. The most common way for web pages to show dynamic data prior to AJAX was by downloading a new web page from the server. For example, consider craigslist.org, shown in Figure 4-1.

image

FIGURE 4-1: Craigslist.org is quite happy with Web 1.0, thank you very much.

To navigate through the categories of listings or search results on Craigslist, you click links that cause the entire page to refresh and reveal the content of the page you requested.

While still very common, refreshing the entire page to display new data in just part of the page is unnecessarily slow and can provide a less smooth user experience.

Compare the craigslist-style navigation with the more application-like navigation of Google Plus, shown in Figure 4-2, which uses AJAX to load new content into part of the screen while the navigation bar remains static.

image

FIGURE 4-2: Google Plus uses AJAX to provide a modern user experience.

In addition to making web page navigation smoother, AJAX is also great for creating live data elements in a web page. Prior to AJAX, if you wanted to display live data, a chart, or an up-to-date view of an email inbox, you either needed to use a plug-in (such as Adobe Flash) or periodically cause the web page to automatically refresh.

With AJAX, it’s possible to periodically refresh data through an asynchronous process that runs in the background and then update only the elements of the page that need to be modified.

Weather Underground’s Wundermap, shown in Figure 4-3, shows a weather map with constantly changing and updating data overlays. The data for the map is retrieved from remote servers using AJAX.

image

FIGURE 4-3: Wundermap uses AJAX to display live weather data.

Viewing AJAX in action

In Figure 4-3, shown in the preceding section, the Chrome Developer Tools window is open to the Network tab. The Network tab shows all network activity involving the current web page. When a page is loading, this includes the requests and downloads of the page’s HTML, CSS, JavaScript, and images. After the page is loaded, the Network tab also displays the asynchronous HTTP requests and responses that make AJAX possible.

Follow these steps to view AJAX requests and responses in Chrome:

  1. Open your Chrome web browser and navigate to www.wunderground.com/wundermap.
  2. Open your Chrome Developer Tools by using the Chrome menu or by pressing Cmd+Option+I (on Mac) or Ctrl+Shift+I (on Windows).
  3. Open the Network tab.

    Your Developer Tools window should now resemble Figure 4-4. You may want to drag the top border of the Developer Tools to make it larger at this point. Don’t worry if this makes the content area of the browser too small to use. What’s going on in the Developer Tools is the important thing right now.

    Notice that new items are periodically appearing in the Network tab. These are the AJAX requests and responses. Some of them are images returned from the server, and some are data for use by the client-side JavaScript.

  4. Click one of the rows in the Name column of the Networks tab.

    Additional data will be displayed about that particular item, as shown in Figure 4-5.

  5. Click through the tabs (Headers, Preview, Response and so on) in the detailed data pane and examine the data.

    The first tab, Headers, displays the HTTP request that was sent to the remote server. Take a look in particular at the Request URL. This is a standard website address that passes data to a remote server.

  6. Select and copy the value of the Request URL from one of the items you inspected.
  7. Open a new tab in your browser and paste the entire Request URL into the address bar.

    A page containing data or an image opens, as in Figure 4-6.

  8. Compare the results of opening the Request URL in a new tab with the results shown in the Response tab in the Developer Tools.

    They should be similar, although they may not look identical because they weren’t run at the same time.

image

FIGURE 4-4: The Network tab of the Developer Tools.

image

FIGURE 4-5: Viewing additional information about a particular record in the Network tab.

image

FIGURE 4-6: The result of copying an HTTP Request URL from the Network tab.

As you can see, there’s really no magic to AJAX. The JavaScript on the web page is simply requesting and receiving data from a server. Everything that happens behind the scenes is open to inspection through the Chrome Developer Tools (or the similar tools that are available with most other web browsers today).

Using the XMLHttpRequest object

The XMLHttpRequest object provides a way for web browsers to request data from a URL without having to refresh the page.

The XMLHttpRequest object was created and implemented first by Microsoft in its Internet Explorer browser and has since become a web standard that has been adopted by every modern web browser.

You can use the methods and properties of the XMLHttpRequest object to retrieve data from a remote server or your local server. Despite its name, the XMLHttpRequest object can get other types of data besides XML, and it can even use different protocols to get data besides HTTP.

Listing 4-1 shows how you can use XMLHttpRequest to load the contents of an external text document containing HTML into the current HTML document.

LISTING 4-1 Using XMLHttpRequest to Load External Data

<html>
<head>
<title>Loading External Data</title>
<script>
  window.addEventListener('load',init,false);
  function init(e){
  document.getElementById('myButton').addEventListener('click',documentLoader,false);
  }
  function reqListener () {
   console.log(this.responseText);
   document.getElementById('content').innerHTML = this.responseText;
  }
  function documentLoader(){
   var oReq = new XMLHttpRequest();
   oReq.onload = reqListener;
   oReq.open("get", "loadme.txt", true);
   oReq.send();
  }
</script>
</head>
<body>
  <form id="myForm">
  <button id="myButton" type="button">Click to Load</button>
  </form>
  <div id="content"></div>
</body>
</html>

The heart of this document is the documentLoader function:

function documentLoader(){
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "loadme.txt", true);
oReq.send();
}

The first line of code inside the function creates the new XMLHttpRequest object and gives it the name of oReq:

var oReq = new XMLHttpRequest();

The methods and properties of the XMLHttpRequest object are accessible through the oReq object.

This second line assigns a function, reqListener, to the onload event of the oReq object. The purpose of this is to cause the reqListener function to be called when oReq loads a document:

oReq.onload = reqListener;

The third line uses the open method to create a request:

oReq.open("get", "loadme.txt", true);

In this case, the function uses the HTTP GET method to load the file called loadme.txt. The third parameter is the async argument. It specifies whether the request should be asynchronous. If it’s set to false, the send method won’t return until the request is complete. If it’s set to true, notifications about the completion of the request will be provided through event listeners. Because the event listener is set to listen for the load event, an asynchronous request is what’s desired.

warning It’s unlikely that you’ll run into a situation where you’ll want to set the async argument to false. In fact, some browsers have begun to just ignore this argument if it’s set to false and to treat it as if it’s true either way because of the bad effect on the user experience that synchronous requests have.

The last line in the documentLoader function actually sends the requests that you created with the open method:

oReq.send();

technicalstuff The .open method will get the latest version of the requested file. So-called live-data applications often use loops to repeatedly request updated data from a server using AJAX.

Working with the same-origin policy

If you save the HTML document in Listing 4-1 to your computer and open it in a web browser, more than likely, you won’t get the results that you’d expect. If you load the document from your computer and then open the Chrome Developer Tools JavaScript console, you will see a couple of error messages similar to the error in Figure 4-7.

image

FIGURE 4-7: Errors when trying to use XMLHttp Request on a local file.

The problem here is what’s called the same-origin policy. In order to prevent web pages from causing users to unknowingly download code that may be malicious using XMLHttpRequest, browsers will return an error by default whenever a script tries to load a URL that doesn’t have the same origin. If you load a web page from www.example.com and a script on that page tries to retrieve data from www.watzthis.com, the browser will prevent the request with a similar error to the one you see in Figure 4-7.

The same-origin policy also applies to files on your local computer. If it didn’t, XMLHttpRequest could be used to compromise the security of your computer.

There’s no reason to worry about the examples in this book negatively affecting your computer. However, in order for the examples in this chapter to work correctly on your computer, a way around the same-origin policy is needed.

The first way around the same-origin policy is to put the HTML file containing the documentLoader function and the text file together onto the same web server.

The other way around the same-origin policy is to start up your browser with the same-origin policy restrictions temporarily disabled.

warning These instructions are to allow you to test your own files on your local computer only. Do not surf the web with the same-origin policy disabled. You may expose your computer to malicious code.

To disable the same-origin policy on a Mac:

  1. If your Chrome browser is open, close it.
  2. Open the Terminal app and launch Chrome using the following command:

    /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --disable-web-  security

To disable the same-origin policy on Windows:

  1. If your Chrome browser is open, close it.
  2. Open the Command prompt and navigate to the folder where you installed Chrome.
  3. Type the following command to launch the browser:

    Chrome.exe --disable-web-security

Once the browser starts up, you’ll be able to run files containing AJAX requests locally until you close the browser. Once the browser is closed and reopened, the security restrictions will be re-enabled automatically.

Figure 4-8 shows the result of running Listing 4-1 in a browser without the same-origin policy errors.

image

FIGURE 4-8: Listing 4-1 run in a browser with the same-origin policy disabled.

Using CORS, the silver bullet for AJAX requests

It’s quite common for a web application to make requests to a different server in order to retrieve data. For example, Google provides map data for free to third-party applications.

In order for the transactions between servers to be secure, mechanisms have been created for browsers and servers to work out their differences and establish trust.

Currently, the best method for allowing and restricting access to resources between servers is the standard called Cross-Origin Resource Sharing (CORS).

To see CORS in action, using the Chrome web browser visit the Weather Underground’s Wundermap (www.wunderground.com/wundermap). When the page has loaded, right-click and select Inspect to open the Chrome Developer Tools, then select the Network tab. Click one of the requests where the Name starts with “stationdata?” and the Type is xhr.

Click the Headers tab, and you’ll see the following text within the HTTP header:

Access-Control-Allow-Origin: *

This is the CORS response header that this particular server is configured to send. The asterisk value after the colon indicates that this server will accept requests from any origin. If the owners of wunderground.com wanted to restrict access to the data at this script to only specific servers or authenticated users, they could do so using CORS.

Putting Objects in Motion with JSON

In Listing 4-1, you use AJAX to open and display a text document containing a snippet of HTML. Another common use for AJAX is to request and receive data for processing by the browser.

For example, gasbuddy.com uses a map from Google along with data about gas prices, to present a simple and up-to-date view of gas prices in different locations, as shown in Figure 4-9.

image

FIGURE 4-9: gasbuddy.com uses AJAX to display gas prices on a map.

If you examine gasbuddy.com in the Network tab, you’ll find that some requests have responses that look something like the code shown in Listing 4-2.

LISTING 4-2 Part of a Response to an AJAX Request on gasbuddy.com

([{id:”tuwtvtuvvvv”,base:[351289344,822599680],zrange:[11,11],
layer:”m@288429816”,features:[{
id:"17243857463485476481",a:[0,0],bb:[-8,-8,7,7,-47,7,48,22,-41,19,41,34],c:"{1:{title:"Folsom Lake State Recreation Area"},4:{type:1}}"}]},{id:"tuwtvtuvvvw",zrange:[11,11],layer:"m@288429816"},{id:"tuwtvtuvvwv",base:[351506432,824291328],zrange:[11,11],layer:"m@288429816",features:[{id:"8748558518353272790",a:[0,0],bb:[-8,-8,7,7,-41,7,41,22],c:"{1:{title:"Deer Creek Hills"},4:{type:1}}"}]},{id:"tuwtvtuvvww",zrange:[11,11],layer:"m@288429816"}])

If you take a small piece of data out of this block of code and reformat it, you get something like Listing 4-3, which should look more familiar to you.

LISTING 4-3 gasbuddy.com Response Data, Reformatted

{id:"tuwtvtuvvvv",
base:[351289344,822599680],
zrange:[11,11],
layer:"m@288429816",
features:[{
id:"17243857463485476481",
a:[0,0],
bb:[-8,-8,7,7,-47,7,48,22,-41,19,41,34],
c:"{
1:{title:"Folsom Lake State Recreation Area"},
4:{type:1}
}"}
]}
}

By looking at the format of the data, you can see that it looks suspiciously like the name:value format of a JavaScript object literal, also known as a comma-separated list of name-value pairs enclosed in curly braces.

The main reason JSON is so easy to use is because it’s already in a format that JavaScript can work with, so no conversion is necessary. For example, Listing 4-4 shows a JSON file containing information about this book.

LISTING 4-4 JSON Data Describing Coding For Dummies

{ "book_title": "Coding For Dummies",
"book_author": "Nikhil Abraham",
"summary": "Everything beginners need to know to start coding.",
"isbn":"9781119363026"
}

Listing 4-5 shows how this data can be loaded into a web page using JavaScript and then used to display its data in HTML.

LISTING 4-5 Displaying JSON Data with JavaScript

<html>
<head>
<title>Displaying JSON Data</title>
<script>
  window.addEventListener('load',init,false);
  function init(e){
document.getElementById('myButton').addEventListener('click',
documentLoader,false);

  }
  function reqListener () {
   // convert the string from the file to an object with JSON.parse
   var obj = JSON.parse(this.responseText);
   // display the object's data like any object
   document.getElementById('book_title').innerHTML = obj.book_title;
   document.getElementById('book_author').innerHTML = obj.book_author;
   document.getElementById('summary').innerHTML = obj.summary;
  }
  function documentLoader(){
   var oReq = new XMLHttpRequest();
   oReq.onload = reqListener;
   oReq.open("get", "listing4-5.json", true);
   oReq.send();
  }
</script>
</head>
<body>
  <form id="myForm">
  <button id="myButton" type="button">Click to Load</button>
  </form>
  <h1>Book Title</h1>
  <div id="book_title"></div>
  <h2>Authors</h2>
  <div id="book_author"></div>
  <h2>Summary</h2>
  <div id="summary"></div>
</body>
</html>

The key to displaying any JSON data that’s brought into a JavaScript document from an external source is to convert it from a string to an object using the JSON.parse method. After you do that, you can access the values within the JSON file using dot notation or bracket notation as you would access the properties of any JavaScript object.

Figure 4-10 shows the results of running Listing 4-5 in a web browser and pressing the button to load the JSON data.

image

FIGURE 4-10: Displaying JSON data within an HTML page.

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

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