Make an AJAX Request from a Joomla! Module

Make an AJAX request from a Joomla! module

Did you know Joomla! 3.2 includes an AJAX Interface? If you've ever needed to make an AJAX request in Joomla! from a custom module, you've probably run into a wall.

Previously, you'd have to create your own component to call a method (index.php?option=com_yourcomponent&task=getSomething). This was an absolute pain for something that should be so simple; well, now it is that simple.

Forming your request URL

Here is an example request URL:


Let's break it down so you can create your own.

  • index.php?option=com_ajax : ALL requests must start with this. You can actually omit the 'index.php' part, but I like to keep it in so my URL isn't starting with a question mark.
  • &module=social : The first part of this is the type of extension you're using. This can either be 'module' or 'plugin'. The second part is the name of the extension. Make sure you're NOT including the 'mod_' or 'plg_', just the name.
  • &method=getTwitter : Here, we're setting the method that will be called by the module/plugin. If you're using this on a module, the method must be appended with 'Ajax'. So, the method represented here will be getTwitterAjax. If you're using this on a plugin, the method must be prepended with 'onAjax'. So, the method represented here will be onAjaxGetTwitter. Confusing, I know.
  • &format=json : Here we're setting the format we'd like to receive from the request. You can use 'debug' instead of 'json' to get "human-readable output of the results".

Setting up the method in your module

You'll need to setup a helper.php file in your module to accomplish this. If this isn't familiar to you, head over to this Joomla! tutorial.

Using the above request URL, the method in our helper.php file looks something like this:

 * Method to get lastest twitter user's tweets.
 * @access    public
 * @return    string
 * @since    1.0
public static function getTwitterAjax(){
    //Get the app
    $app = JFactory::getApplication();
    //Insert stuff to do here
    //echo the data
    echo json_encode($data);

    //close the $app


In our module's template file, we access this method using jQuery like so:

    //Get twitter feed
    $.get('index.php?option=com_ajax&module=social&method=getTwitter&format=json', function(data){
        //parse the JSON
        var response = jQuery.parseJSON(data);
        //do something with the JSON object

Joomla! has provided a couple examples of a module & plugin using the Joomla Ajax Interface.