How to Use Joomla’s Ajax Interface Component (com_ajax)

Last week, we were commissioned to build a tool that displays a list of state representatives on the website of a company producing soda dispensers. The tool consisted of a simple dropdown, containing all the American states, and, based on the selected state from the dropdown, the tool displayed the representatives serving the selected state.

Of course, there are many ways to do this, but we decided to do this using Ajax, but not just any Ajax; we wanted to use Joomla’s Ajax interface (yes, we know that Ajax is the same across the board, but you know what we mean).

Now, before telling you how we did it, let us explain a bit what Joomla’s Ajax interface is… You see, Ajax, at its purest and simplest form, consists of a request to a server and a response from a server, the request is made through JavaScript, and the response is sent through JavaScript, but typically, the latter is generated on a server by a PHP file (in the case of a PHP based environment). In order to avoid clutter and to stick with the MVC pattern, Joomla comes bundled with a component called Ajax Interface, which allows the programmer to get the response data from a module or a plugin. Unfortunately, many Joomla programmers out there don’t know that this component actually exists, so they create non-Joomla PHP files on the server in order to serve Ajax responses. What’s even more unfortunate, is that most of the remaining programmers that know about Joomla’s Ajax interface are intimidated by it (we have to admit we were among these people), mistakenly believing it’s a monster that is hard to work with, while the reality is the absolute opposite (and we are going to demonstrate that in this post).

So, how did we do it?

Well, the first thing that we did was create a K2 module called K2 Representatives (mod_k2_representatives), that queries the #__k2_items database for specific items where an extra field matches the value of the state passed as a GET variable in the PHP $_GET array.

The module consisted of the following 4 files:

  • index.html: An empty HTML file which should be in every Joomla folder for security reasons.
  • mod_k2_representatives.xml: This is the XML manifest of the module – standard stuff.

  • mod_k2_representatives.php: This is the main module file. It just contained the following 3 line:

    defined('_JEXEC') or die ;
    require_once (dirname(__FILE__).'/helper.php');
    $items = modK2RepresentativesHelper::getItems($params);

  • helper.php: The module helper file. This file contained just 2 methods (within the modK2RepresentativesHelper class) which handled all the logic of the module. These methods are:

    • public static function getItems(&$params, $format = ‘html’): We copied this function from the helper file of the K2 content module and we modified it to accommodate our needs. The function returned the items with extra items matching the GET state.
    • function getRepresentativesAjax(): This function called the static getItems function, and transformed the returned data into a well formatted string.

We then created a Joomla article containing the following code:

<script type="text/javascript">
var jQueryRepresentatives = jQuery.noConflict();
jQueryRepresentatives(document.body).on('change','#state',function(){
	jQueryRepresentatives.ajax({
		type: 'GET',
		url: "http://www.[ourclientjoomlawebsite].com/index.php?option=com_ajax&module=k2_representatives&format=raw&Itemid=300&method=getRepresentatives&state="+jQueryRepresentatives('#state').val(),
		success:function(data){
			jQueryRepresentatives('#results').html(data);
		},
		error:function(){
			jQueryRepresentatives('#results').html('<p class="error">An error was encountered while retrieving the representatives from the database.</p>');
		}
	});  
});</script>

<form action="" method="post"><strong>State:</strong>
	<select id="state">
		<option value="NA">Select a State</option>
		<option value="AL">ALABAMA</option>
		<option value="AK">ALASKA</option>
		<option value="AZ">ARIZONA</option>
		...
	</select>
</form>
<div id="results"> </div>

Now – the essence of the above is this line:

url: "http://www.[ourclientjoomlawebsite].com/index.php?option=com_ajax&module=k2_representatives&format=raw&Itemid=300&method=getRepresentatives&state="+jQueryRepresentatives('#state').val()

  • The module GET variable should contain the name (not the title) of the module to get the data from. In our case, it is k2_representatives (notice that it doesn’t contain the mod part, e.g., it is k2_representatives and not mod_k2_representatives). If you provide the name of a module that doesn’t exist (or is disabled), then the Ajax interface will return the following error:

    LogicException: Module mod_k2_representatives is not published, you do not have access to it, or it’s not assigned to the current menu item.

  • The Itemid GET variable should contain the ID of the menu item that this module is assigned to. The Itemid must be correct – or else you will get the same error as when you provide a wrong/disabled module name.

  • The method GET variable should contain the name of the function that the Joomla Ajax interface should call in order to grab the data from. Now, you may notice that we don’t have a function called getRepresentatives, but, in the helper file, we have a function called getRepresentativesAjax. The thing is, the Joomla Ajax interface insists that any function it calls must end with Ajax. That is OK, because it is possibly done this way in order to avoid conflicts and to allow the developers to have a different output for the Ajax interface (than that of the standard module output). The odd thing is that the Ajax method should not contain the word Ajax (well, technically, it can, but in that case, the method in the helper file should be called something like getRepresentativesAjaxAjax [yes – you should have the word Ajax twice in your method]). So if, in your Ajax call, the method name is myFunction, then you should have in your helper file a function called myFunctionAjax, if you don’t have such function, then you will see the following error:

    LogicException: Method myFunctionAjax does not exist.

  • The state GET variable grabs the current selected state for data filtering.

  • The rest of the GET parameters are static and should not be changed. You should always have option=com_ajax and format=raw in your Ajax request.

The above, as you can imagine, worked as a charm, and the client was happy with the clean end result, and we were happy with the clean way it was done.

If you want to use Ajax on your Joomla website, then follow the above guide and you will not be disappointed. If you need help with the implementation, then please contact us. We are always available, we will finish your job quickly, and our fees are very affordable!

No comments yet.

Leave a comment