AJAX-ify your Joomla! website

Since the release of CoolPlanet 2009, I often get the question how to implement AJAX in a Joomla! 1.5 component. As Joomla! makes use of the Model View Controller design pattern, it becomes very easy to make your brand new website even more shiny with a fresh mix off JSON, Mootools and PHP.

You probably already noticed, the filename of almost every view in a Joomla! 1.5 component is view.html.php, because most of these views output HTML. AJAX however, likes to talk with XML or JSON because the data gets sent from the server to client without a page refresh, hence the asynchronious in Asynchronous Javascript And XML.

So the right question would be how to leverage right data the JSON. Simple! Besides your original HTML view, create a JSON view: view.json.php! As previously mentioned, a HTML view outputs HTML. A JSON view outputs JSON, meaning that you need to encode your data in JSON: JSON view snippet 1. No need to call JView::display(), as this methods will try to load a template file. We don't want a template file for a JSON view. Instead, we want just rough JSON data (json_encode()) to process in our HTML view.

You may wonder what the difference of JSON against HTML is. Let me just compare the output that both views generate: JSON/HTML comparison1. You clearly see in the HTML view the tags for markup purposes, while the JSON view just outputs rough data.

Next, we need some Javascript to retrieve and process this JSON-formatted data, and attach some DOM events to HTML elements. In my example, I attached a change event (Javascript snippet3) to my list, so when the selection changes the component makes a JSON call to the server to retrieve the data. This data gets injected into the page, so the body changes without a page reload. Note: you need tell Joomla! that you want the data in the JSON format, by appending format=json to your request URL.

This was a short introduction on how to improve your component with AJAX. You can achieve the same result with XML, if you don't like JSON that much. The only thing you need to create is an XML view, where you encode your data in XML.

You can download the sources to play with the component and review the code used in this example.

You can also look again at the code snippets, mentioned above:

  1. JSON view snippet
  2. JSON/HTML comparison
  3. Javascript snippet

Tell us what you think!


Recent comments

Blog Archive