AJAX - The Complete Reference

(avery) #1

30 Part I: Core Ideas


users regardless of submission method, so considering what might go wrong is a necessity.
For example, in the case of a form posting, the user may submit a tremendous amount of
data in the comment field; thus it is necessary to limit the size of data that is written to the
file on the server. One possibility is rejecting the entire submission if it exceeds a boundary
condition or simply truncating it to fit a predetermined limit. Because this example is a one-
way communication pattern, it makes the most sense to silently truncate any parameters
that exceed 1024 characters.
Even if form submissions are within predefined size limits, submitted data must be treated
cautiously. For example, if users were to submit (X)HTML markup, particularly markup that
includes JavaScript, they may be attempting to create a cross-site scripting exploit. To combat
such problems, the server side code should use techniques to normalize any received data,
particularly (X)HTML tags, into some safer escaped format. As a demonstration, a short
snippet of code changes to sanitize submitted data in setrating.php is shown here:

/* pull the user ratings via the query string */
if (isset($_REQUEST['rating']))
$rating = htmlentities(substr(urldecode($_REQUEST['rating']),0,1024));
else
$rating = 0;
if (isset($_REQUEST['comment']))
$comment = htmlentities(substr(urldecode($_REQUEST['comment']),0,1024));
else
$comment = "";

Clearly this is just the tip of the iceberg, but we have all of Chapter 7 to get into many of the
security challenges facing Web developers.

Cookie-based Transport

As a final one-way communications example, we note that headers can be used to send
data. Of course, without an XHR to work with, it is pretty difficult to set any HTTP headers
save one, the Cookie header. In order to send the cookie value, simply make a new location
request to the server, expecting a 204 as before. However, because there is no query string, it
is necessary to separate out each individual name-value pair to store in the cookie. A similar
technique was used in the form post example. To do this, an object literal is created for the
payload with each property and value set equal to the individual name-value pairs, as
shown in the next code fragment. This is pretty much a subset of a data format called JSON
(JavaScript Object Notation) that you will become quite familiar with later, particularly in
Chapter 4.

/* form payload object with rating and transport name/value pairs */
var payload = {"rating":rating, "transport":transport};

The cookie transport version of sendRequest() function is shown next:

function sendRequest(url,payload)
{
for (var key in payload)
document.cookie = key+"="+payload[key]+"; path=/";
window.location = url;
}
Free download pdf