Thursday, April 20, 2006

Ajax: HTML vs XML responses

A friend of mine has a discussion on his blog regarding returning straight HTML or XML in your AJAX responses (see What type of data should an Ajax call return?)

I voiced a comment regarding my appreciation for the direction used by Rico where XML is always returned, though it may contain an HTML snippet such as:


<ajax-response>
<response type="element" id="personInfo">
[valid XHTML here]
</response>
</ajax-response>


where the type="element" id="personInfo" indicates to Rico to replace the innerHTML of the element with id personInfo with the contents of the response.

Or alternatively:


<ajax-response>
<response type="object" id="formLetterUpdater">
[valid XML data here]
</response>
</ajax-response>


The type="object" id="formLetterUpdater" calls a JavaScript object registered under the name matching the id of formLetterUpdater. That Javascript would then process the contents of the response as XML to extract whatever data is necessary.

For either mechanism, multiple "response" clauses can be returned in a single "ajax-response" allowing multiple sections of a web page to be updated from a single AJAX action if necessary.

My apprehension about this method is that the server side processing has too much knowledge about how the data will be used (by dictating the ids). Of course, that might be able to be handled by having the AJAX response send which ids it wants data for.

Of these two mechanisms from Rico, I think the XML data mechanism has the most flexibility, as it describes the data in XML and the UI can extract what it needs and format it correctly whether by coding manual JavaScript DOM processing as indicated with the formLetterUpdater above, or by utilizing XSLT on the browser to format it as desired. Using XSLT provides multiple advantages for formatting and re-formatting the data for the user without the need to communicate with the server over and over to format the HTML. For example, switching themes, languages, or switching from a table to a graph.

No comments: