Ajax in Joomla with jQuery

Sometimes you need Joomla to give you nothing but the components output. No template, no styling, nothing. Just the output. This article shows you how to do this, and tie it in with an Ajax call.

This article came about while I was building a custom Joomla component at work, the component required a multi step form that stayed on the same page. So data needed to be grabbed from the database and displayed on the screen as the user was filling in the form.

I wont go into the details of making a custom component as that is outside the scope of this article, more information on that can be found here, instead we’ll just grab an article assuming that it belongs to a menu and has the Itemid of 10 (you can call absolutely any component you like, as long as you know the non SEF link to the page you are after).

First of all we need to load jQuery, we’ll load this from Googles server to reduce the load on our own server

?View Code JAVASCRIPT
1
2
3
4
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
	jQuery.noConflict();
</script>

We’ll also need to setup a new file in the /templates/system/ folder called barebones.php that will be called when we make our Ajax calls instead of the normal template so that the data returned doesn’t include the main template, css, javascript etc. Create the file, and enter in the following:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
/**
 * @copyright	Copyright (C) 2009 subooa.com. All rights reserved.
 * @license	GNU/GPL, see LICENSE.php
 * @author	Chris Duell (subooa.com)
 * barebones is a stripped template by subooa. 
 */
 
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
?>
<jdoc:include type="component" />

Now to making the Ajax call, you will need a place to put the data once it is loaded, so create a div with the id of “ajax_here”.

Using jQuery, the Ajax call is pretty striaght forward:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
jQuery(document).ready(function(){
	jQuery.ajax({
		type: "GET",
		url: "index.php",
		data: "?Itemid=10&tmpl=barebones",
		success: function(html){
			jQuery("#ajax_here").html(html);
		}
	});
});

Quickly stepping through this, we are making a call to index.php and requesting the article associated with Itemid 10, and after the data is received adding it to the div that we created earlier that has the id of “ajax_here”. But most importantly, we explicitly call the “barebones” template so the data returned and entered into the div is ONLY the output for the component, nothing more.

I highly recommend using Firebug as you are developing and testing this so that you can see if the Ajax calls are being correctly made, and the expected results are being returned.

This article is quite basic on purpose, however if you would like more information just leave a comment.

Back to Top