Chapter 8. Simplified Client-Server Communication and Data

The oldest client-server communication technique is Ajax, and it’s still the most widely used. In a nutshell, the procedure consists of preparing a request to the web server, typically as a POST or GET request, making the request, and assigning a callback function to process the result. In the callback function, server responses are tested until a successful response is received and the result is processed—either an acknowledgment is made that the request was successful (POST), or the returned results are processed (GET).

The data that passes between the client and server can be simple text, or it can be formatted as XML or JSON. The latter is becoming the increasingly popular choice, with most server-side technologies providing APIs that generate and consume JSON.

Note

This chapter focuses on Ajax, only, as well as basic processing of text, XML, and JSON data. Chapter 14 covers other, more leading-edge client-server communication techniques.

Handling an XML Document Returned via an Ajax Call

Problem

You need to prepare your Ajax application to deal with data returned in XML.

Solution

First, ensure the application can handle a document with an XML MIME type:

if (window.XMLHttpRequest) {
   xmlHttpObj = new XMLHttpRequest();
   if (xmlHttpObj.overrideMimeType) {
       xmlHttpObj.overrideMimeType('application/xml');
   }
}

Next, access the returned XML document via the XHMLHttpRequest’s responseXML property, and then use the DOM methods to query the ...

Get JavaScript Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.