Ajax reqest in joomla 1.6 and later – Due to Mootools version change in joomla 1.6, ajax request would not work the way it used to work in joomla 1.5. In this article we would discuss how to get ajax request in admin part of a joomla component for version higher than 1.5. We will take a typical example of Loading state of a country so that even a new joomla developer can understand it.
How to create an Ajax reqest in joomla 1.6
I suppose you are following MVC architecture while developing your joomla component. In the edit view of your component open edit.php file (or whatever if you have renamed it). Render the country form field like below –
- form->getLabel(‘country’); ?> form->getInput(‘country’); ?>
Now add below code to load your default state list box –
- form->getLabel(‘states’); ?> form->getInput(‘states’); ?>
Note the span tag with ID “ajax-container”. We will load the list of state returned by ajax request here once a user changes country from the above dropdown. We are not done with the html part of our ajax request.
Ajax reqest in joomla 1.6
Now we will add a onchange event to our country dropdown using below javascript –
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(); } ); });
Now we will create a function in controller file of our component that 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>'; }
That’s it. Your ajax request should load states of the selected country. Please use the comment box below if you face any problem with the above code. Please also comments if you think there is a better way to use ajax in admin part of a joomla component.