Server-Side XML and JSON

Creating custom XML or JSON structures with a server-side language from database data and returning it as a response to an XHR is a required step for creating Ajax-enabled database integration.


Although we have already briefly covered the structuring of dynamic data as an XML structure to be used as an Ajax response, in this section we will focus more on the server side of the process. Responding with valid XML requires a few easy steps that can be achieved by the following instructions.

Including an XML Declaration

In order to specify that our data structure is XML, we must add an XML declaration to the beginning of the file that we would like to return to the client side. The following code shows an example of how to add this declaration to the structure and how to also specify the format in which the XML data should be encoded by the server.

$declaration = "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>";

Setting the Content Type to Text/XML

Setting the content type is what we have been doing in the serviceConnector.php file that we created in each of our server-side examples. Setting the header to this content type is the key to creating a valid XML structure that is accessible by other languages, such as JavaScript. Following is an example of the header we have been using to make our structures valid.

header("Content-Type: application/xml; charset=UTF-8");

The last thing to remember is to carefully structure the string that you want to ultimately use as the XML response with opening and closing XML tags surrounding the dynamic data. This may seem the most obvious part of the process, but is usually the most likely to be an issue.


Responding with data as a JSON structure allows us to simply convert the JSON structure into a JavaScript object on the client side. After the data has been received by the Ajax engine as a response, we can pass it to our custom parsing method. This method simply needs to use the eval method to convert the data into a valid JavaScript object. This leaves us with a fully functional JSON object that can be used for anything we want to achieve on the client side. If we are trying to achieve this functionality, it makes the architecture of the JSON response structure a very important piece of the process.

If we plan on sending a response back to the client as a JSON structure, we must write a custom method to concatenate the data as a JSON object that can be evaluated on the client side by JavaScript after the Ajax engine receives the response, or we can use one of the parsers available at

Ajax for Web Application Developers
Ajax for Web Application Developers
ISBN: 0672329123
EAN: 2147483647
Year: 2007
Pages: 129
Authors: Kris Hadlock

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: