AJAX - The Complete Reference

(avery) #1

132 Part I: Core Ideas


Now this XML document must be converted into a string in order to transmit to the
server. Once again, the different browsers have different ways to serialize a DOM tree.

if (typeof XMLSerializer != "undefined")
payload = (new XMLSerializer()).serializeToString(xmlDoc);
else if (xmlDoc.xml)
payload = xmlDoc.xml;

Everything follows as before, including making sure to set the proper request header.
The network transmission is omitted as it looks the same as the previous example, but if
you want to play with the client-side code it can be found at http://ajaxref.com/ch4/
xmldomrequest.html.
Regardless of how the XML packet is created, dealing with it on the server side is going
to be the same. The raw request data stream will need to be read and then parsed as XML.
Here’s an example of doing this in PHP:

$payloadString = $GLOBALS['HTTP_RAW_POST_DATA'];
$payloadArray = array();
$doc = new DOMDocument();
$doc->loadXML($payloadString);
$children = $doc->documentElement->childNodes;
for($i=0;$i<$children->length;$i++)
{
$child = $children->item($i);
$payloadArray[$child->nodeName] = $child->nodeValue;
}

After running this code, an associative array that relates the nodes to their contained
values will be ready to be used. Of course, there might be many other ways to use the XML
data, but regardless, it is clear that even with plain old XML, there is going to be some work
on both sides of the transmission.

JSON


Since we are coming from JavaScript, it might be convenient to use a JavaScript friendly data
format as our transport: enter JSON (JavaScript Object Notation), defined at http://www.json.org.
JSON is a lightweight data-interchange format that is based on a subset of the JavaScript
language. However, it is actually pretty much language independent and can easily be
consumed by various server-side languages.
The values that are allowed in the JSON format are strings in double quotes like
“Thomas”; numbers like 1, 345.7, or 1.07E4; the values true, false, and null; or an array
or object. The syntax trees from JSON.org show the format clearly so we present those here
with a brief discussion and set of examples.
Free download pdf