AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 169


PART I


xhr.send(null);
}
}

Now when the XHR returns with data, put the XML content into the hidden <xml> tag.
Then find the table and various fields you plan on populating. Finally collect the data from
the <xml> tag and fill the table in with the fetched content.

function handleResponse(xhr)
{
if (xhr.readyState == 4 && xhr.status == 200)
{
var xmlDoc = document.getElementById("xmlBookmarks");
xmlDoc.innerHTML = xhr.responseText;
var xmlTable = document.getElementById("mainbody");
var xmlFields = new Array();
xmlFields = getDataFields(xmlTable, xmlDoc, xmlFields);
fillTable(xmlTable, xmlFields);
}
}

With the general algorithm in mind, you should now look at the complete example with
all of its DOM code at http://ajaxref.com/ch4/xmldataisland.html. This is by no means a
completely generic solution for data islands in XHR-capable browsers, but it wouldn’t be
that hard to extend it to be.

Binary Responses


Ajax developers often ask on message boards if it is possible to pass multimedia data like
images back as a response to an XHR. The answer given is almost always no: you can pass
back a URL of the image to fetch, but sending the raw binary image data is not possible.
Some may further point out that even if passing such data were possible, there is no evident
way to use such content. Well, it turns out there may be some interesting possibilities here if
you extend your thinking to consider receiving a text-encoded binary-like format such as a
base64-encoded message in responseText. Encoded data may be useful, as previously
mentioned, for a light form of visual security, so we’ll start with that as an example.
However, if you combine this idea with an esoteric data: URL format you can see you
might actually fetch images with XHRs.

Encoded Content: Base64

Earlier in the chapter, we discussed the use of base64-encoded content in requests and
similarily it is easy enough to generate such content on the server and send it back as a
response as shown here:

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/plain");
header("Content-Transfer-Encoding: base64");
$msg = "Thank you for voting. You rated this a <strong>$rating</strong>.
Free download pdf