152 Part I: Core Ideas
If you are creating the data to be evaluated, this is most likely safe. If the user is creating
it and you are mirroring it back, this is very unsafe. You will see this problem very clearly in
Chapter 7.
Regardless of the specific problem, given the mischief some Internet users make, it is
a bit too trusting to go with a direct evaluation. It is far safer to look at the data a bit first
before using it. To do this, include the JavaScript JSON library mentioned earlier available
at http://json.org:
<script src="json.js" type="text/javascript"></script>
Next, use the parseJSON() method to look to see if the packet looks correct. This really
adds no major amount of security since it just looks to see if the format looks correct and
unexpected characters are not encountered; if “these conditions are met” or “so”, it does an
eval() as we saw before.
var jsonObject = xhr.responseText.parseJSON();
var rating = jsonObject.rating;
var total = jsonObject.votes;
var average = jsonObject.average;
However it is a step in the right direction and more ideas that will improve the format
such as wrapped JSON will be presented in Chapter 7. Once the JSON data is in hand, it is
inserted into the page as in the other examples. The JSON example can be found at http://
ajaxref.com/ch4/jsonresponse.html.
JSON is currently the data format of the moment as it balances data size and simplicity
of creation and consumption. It is starting to become so popular that more than one pundit
has declared JSON to be the “X” in Ajax. But don’t stop reading now just because you have
discovered JSON; Ajax applications utilizing XML responses really do have some interesting
possibilities of their own.
XML Responses and Handling
XML is an attractive data form for sending responses because there is typically support for
XML creation in most server-side programming frameworks. In addition, the format is quite
descriptive, which aids in long-term maintenance, and browsers provide numerous XML
handling features starting with the simple fact that correctly formed XML response data will
be properly parsed and made available as a DOM tree through the XHR’s responseXML
property.
As in previous examples, you see that creating a data response packet can be a matter of
simply printing out the appropriate structures and setting the correct MIME type for the
Content-Type response header. In this PHP fragment we use a simple XML structure that
is just syntactically well-formed and avoid the use of a DTD or Schema for the moment.
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/xml");
$message = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<pollresults>
<rating id=\"rating\">$rating</rating>
<average id=\"average\">$average</average>