Ajax in Joomla with jQuery
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
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:
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:
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.