Ajax: returning html snippets

A response from Paul Wilkins in an earlier post pointed me to Jeremy Keith’s book Bulletproof Ajax. Among the disadvantages of returning HTML as a response Keith writes

Sending an HTML fragment in an Ajax response … doesn’t work so well if you want to update parts of the same document.

I don’t understand the issue. Can you clue me in?

(FYI Keith continues the above statement with:

In such cases, it’s better to use XML or JSON which can be parsed very precisely

My guess;

example 1:
Don’t return a string such as “<div><ul><li>one</li><li>two</li></ul></div>” but rather an array of elements which are added to the relevant DOM nodes.

example 2:
Don’t return a simple string such as “<a title=“my link title” href=“http://mylink.com”>my link</a>”, when you could build that DOM element and attach it to the correct node from something such as:
(pseudo array)

{ 'title': 'my link title', 'href': 'http://mylink.com' }
{ 'title': 'my link title2', 'href': 'http://mylink2.com' }

Keep data as data for as long as you can on its journey.

There are advantages and disadvantages to both, it depends on what you want to accomplish. In most cases where you would merely like to avoid a page refresh returning HTML is the simplest, and most DRY approach. In the case where you need to format data differently, or need insight regarding possible errors JSON or XML is more appropriate. Essentially, if functionality degrades gracefully adding AJAX will likely result in replacing content with HTML dynamically. There is no reason to return XML and replicate formatting logic. Again though it all depends on what your doing but 90% of the cases I work with return HTML or XML, with HTML in a cdata so that error messages and such can easily be accessed, but HTML can also be easily replaced. Another important thing to consider is any REST based service created makes the data easily accessible to the public. Returning HTML, makes data much less accessible, to possible thieves and such. When I say REST I pretty much mean a URL (endpoint) that returns XML or JSON, as opposed to HTML.

Here’s the challenge I’ve set for myself.

The page sets up a delivery appointment for the user. Within the page are form inputs for the client name / address and the payor name / address.

Given that both the client and (if different) payor names must be prior-registered within the system, I thought I might provide input fields for only the names and use, say, an onblur event to invoke Ajax to the server to get and display the address block.

Yet that would require updating different parts of the same document (one for the client <div> and one for the payor <div>), which the quote from Keith’s book claims is inappropriate.

[Note that I am saving the Ajax component for a later release after I get a stable PHP5/XHTML application running]

It would probably be best to use XML or JSON in that case. Your would essentially need a RESTful service returns the address information given a name. You would then parse it using JavaScript and set the value property for each corresponding form element.


$data = array();
$data["client"]["address"] = "58 nebo rd";
$data["payor"]["address"]  = "52 ronny rd";

$data = json_encode($data);

echo $data;

Which will give you…

{"client":{"address":"58 nebo rd"},"payor":{"address":"52 ronny rd"}}

Parse through it like this…

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<div id="payor"></div>

<div id="client"></div>

<script type="text/javascript">
	var name = $('#username').text();
	$.getJSON('json_page.php?name= + name', function(data) {
		var items = [];
		$.each(data, function(key, val) {
			$('#' + key).html(val.address);

Lets you update each div based upon what was encoded.

Holy Syntax, Batman!

A little overwhelming for an Ajax wannabe.

Appreciate the example.

Will study this and truly appreciate your responses.

I probably should have explained it a little more.

The PHP file I gave you is an array (as you can see, duh). The client and payor section of it, that’s going to be the ID of your div.

So if your div is:

<div id="payor_data">


Then you need to make your array:


When you visit that page, it will spit out that JSON encoded data, that Javascript will sort through.

All the Javascript does is to get a username (From a username field… or whatever) and pass it along to the JSON PHP page.

Then, it gets the JSON, decodes it, and for each of the items (payor… client… whatever you want to add)… it sets the inside of that DIV to the contents of address.