How to Implement Ajax in a Joomla Module?

Ajax (Asynchronous JavaScript and XML) allows web developers to make the user experience far more interactive. Developers make use of this tool to on the client-side to create asynchronous web applications. The biggest advantage of this technology is the fact that it allows the web applications to send data to, and retrieve data from, a server asynchronously. This data exchange happens without interfering with the display and behavior of the existing page. Ajax shouldn’t be misunderstood for being a single technology but it is actually a group of technologies. HTML and CSS can be used in combination to mark up and style information in Ajax. Joomla developers make use of this technology to better the experience of their users. Before we get deep into installation of Ajax in a Joomla module let us take a look at some of the advantages that Ajax offers when you are thinking of creating an interactive website.

  • Faster Page Loads – Sending and receiving data becomes faster when Ajax is implemented in Joomla. This means that the user experiences faster page updates. Ajax uses a JavaScript function that checks and collects values from the submitted form and this data is send to a server side function thus speeding the page load process.
  • Minimal Data Transfer – Since all the data would be sent to the main server, this will avoid post back. Utilization of the net is minimized and the work also becomes faster. In turn the network performance gets enhanced a lot.

Steps to Implement Ajax in Joomla Here we shall take a look at a way to implement a simple Ajax functionality using mootools 1.3 in joomla 1.6 or higher. In the first we shall add Ajax code to view html page – components/com_xxx/views/view/default.php


<?php
JHTML::_('behavior.mootools'); /* to load mootools */
$ajax = "
/* <![CDATA[ */
window.addEvent('domready', function() {
$('start_ajax').addEvent('click', function(e) {
e.stop();
var url = 'index.php?option=com_xxxx&view=xxxxxx&task=updateAjax&format=raw';
var x = new Request({
url: url,
method: 'post',
onSuccess: function(responseText){
document.getElementById('ajax_container').innerHTML = responseText;
}
}).send();      //  To pass values :    }).send('country_id=' + document.getElementById('country_id').value );
});
})
/* ]]> */
" ;
$doc = & JFactory::getDocument();
$doc->addScriptDeclaration( $ajax );
?>

<div><a id="start_ajax" href="#">Click here</a> to start Ajax request</div>
<div id="ajax_container">
Here is the ajax output
</div>

In the second step we shall add a task function to controller – components/com_xxxx/controller.php


function updateAjax() {
//      $country_id=JRequest::getVar('country_id');
echo date('Y-m-d D H:i:s');
}

Now that we have discussed the way in which you can implement Ajax function in Joomla let us take note of ways in which you can call an Ajax function in a Joomla website. We shall load the state of a country in this example.


document.addEvent( 'domready' ,  function() {
$('jform_country').addEvent( 'change' ,  function() {
$('ajax-container').empty().addClass('ajax-loading');

//Ajax Request start here

var myElement = document.getElementById('ajax-container');
var cid = document.getElementById('jform_country').value;
//alert(cid);
var myRequest = new Request({
url: 'index.php?option=com_country&view=items&task=getstates&format=raw',
method: 'get',
evalResponse: 'true',
data: {
'id' : cid,
},
onRequest: function(){
myElement.set('text', 'Loading. Please wait...');
myElement.addClass('loading');
},
onSuccess: function(responseText){
myElement.set('html', responseText);
myElement.addClass('success');
},
onFailure: function(){
myElement.set('text', 'Sorry, your request failed :(');
myElement.addClass('error');
}
}).send();

} );
});

Here we shall also have to create a function in controller file of our component. This function would respond to our Ajax request. Open controller.php located at administrator/components// and below function in that –


function getvendors()
{
$db     =& JFactory::getDBO();
$query = 'SELECT id, title FROM #__product_vendors where published = 1 and catid  =  '.JRequest::getInt('id');
$db->setQuery( $query                  );
$vendors = $db->loadObjectlist();
echo '<select id="jform_vendor" name="jform[vendor]">';

echo '<option value="0">-- Select --</option>';
for ($i=0, $n=count( $vendors ); $i < $n; $i++)
{
$row = &$vendors[$i];
echo '<option value="'. $row->id.'">'.$row->title.'</option>';
}
echo '</select>';
}
</pre>

<p>The states of the country will now be loaded on request.</p>'</pre>'</pre>'</pre>'</pre>'</pre>'</pre>'</pre>'</pre>'