Handling the server side of Ajax requests

From Joomla! Documentation

Revision as of 04:44, 17 September 2009 by Chris Davenport (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The server side of your Ajax implementation may be a public web service, in which case it is already written for you. But if you need to write the server code too then it makes sense to base the code on the Joomla Framework. Although it might be tempting to implement the server code outside Joomla, you will miss out on a number of important security features that make writing secure Ajax server code very simple.

Typically you will want the server to send its response in XML or JSON format. The Joomla 1.5 support for the MVC design pattern makes this particularly easy to arrange. Simply add a new view class into the views directory in a file called view.xml.php or view.json.php depending on the format required. Sometimes the response required to a particular request is so simple that setting up a new view would be overkill. In that case there is no problem in generating the output directly in the controller; no view required.

Generating JSON output

PHP has native functions to encode and decode JSON data. You can encode data using the json_encode function, like this:

// Set up the data to be sent in the response.
$data = array( 'some data' );
// Output the JSON data.
echo json_encode( $data );

The json_encode function can encode almost all data types, such as strings, arrays and objects, although you may need to be aware that the corresponding json_decode function will only return an object (or optionally, an associative array).

It is good practice to set the MIME-type for the output correctly. In some applications you might also want to change the suggested filename to something other than the "index.php" that you will probably get by default. In the following example the suggested filename is changed to the name of the view, with a ".json" extension added.

// Set up the data to be sent in the response.
$data = array('some data');
// Get the document object.
$document =& JFactory::getDocument();
// Set the MIME type for JSON output.
// Change the suggested filename.
// Output the JSON data.
echo json_encode($data);

Generating XML output

Joomla supports a simple and quite efficient class, JSimpleXML, which can be used to generate XML output in, for example, an Ajax implementation. However, using an object-based XML generator suffers from the drawback that it tends to be slow and memory-intensive, even though JSimpleXML is a lightweight implementation. Unless your requirements are particularly complex, directly outputting XML in string form will result in faster response times and a lower server footprint.

For example, the following code will output an XML document consisting of a root element, called <root>, containing an <items> element which itself contains one or more <item> elements with the actual data. You will need to adjust the code to cope with your particular data requirements.

$document =& JFactory::getDocument();
$document->setMimeEncoding( 'text/xml' );
// Output XML header.
echo '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
// Output root element.
echo '<root>'."\n";
// Output the data.
echo "\t".'<items>'."\n";
     foreach($data as $datum){
          echo "\t\t".'<item>'."\n";
          foreach ($datum as $key => $value) {
               echo "\t\t\t".'<'.$key.'>'.htmlspecialchars($value).'</'.$key.'>'."\n";
          echo "\t\t".'</item>'."\n";
echo "\t".'</items>'."\n";
// Terminate root element.
echo '</root>'."\n";

Note that the data should be passed through htmlspecialchars to ensure that HTML characters are properly escaped.

Note also that in this example some attempt has been made to "pretty print" the XML output with tabs and carriage returns. This is not strictly necessary and these extra characters can be removed if you prefer.