How to use ajax in a joomla component
You can add more interactivity to your Joomla site by using ajax. There are a lot of ways you can implement ajax functionality in your Joomla component. I am explaining here the most simple method that I have found to use Ajax. But before coming to the topic, I want to throw some light on how a typical Ajax request works.
How a typical ajax request works
Without Ajax, interaction between the user and the web server takes many different steps.Through ajax, interaction becomes more responsive as the user gets the response back without even clicking a button. The figure below illustrates the process of a typical request through Ajax.
This is the whole process of submitting a typical form to the server through a web page, using Ajax. It is clear from the above figure that all the processes are occurring in the background and the user directly interacts with the web page if all the authentication is okay. All of this happens asynchronously and without requiring a page refresh.
Using ajax in Joomla
First of all, I am going to create a simple text field and a button and on the clicking of the button, information will be saved in a database table through PHP and all this process will occur without a page refresh.
<div id="results"></div>
<input type="text" name="name" id="name" value="">
<input type="button" class="button" id="savename" value="Save Name">
As you can see that I have not given the form element here, nor I have declared the button as type “submit”. Copy and paste the above code in your default.php file of component view. Below this code, write the following.
<?php
$document = JFactory::getDocument();
$document>addScript('http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
$document->addScript('/components/your-component/js/ajax.js');
?>
Create a folder in your component main directory, named “js” and create a file named ajax.js to put our javascript code, which will send an asynchronous request to the server. I am using jQuery here for this. Now open the ajax.js file and put the following code there.
jQuery(document).ready(function(){
jQuery("#savename").click(function(){
var name = jQuery('#name').val();
// you can apply validation here on the name field.
jQuery.post("/components/your-component/ajax.php?name="+name , {
}, function(response){
jQuery('#results').html(jQuery(response).fadeIn('slow'));
});
});
});
Create a file named “ajax.php” in components/your-component directory. In the above js code, we are sending a request to this ajax.php file, providing the name, captured from name field, for processing. Now lets move to ajax.php file and do some PHP work.
<?php
define( '_JEXEC', 1 );
// defining the base path.
if (stristr( $_SERVER['SERVER_SOFTWARE'], 'win32' )) {
define( 'JPATH_BASE', realpath(dirname(__FILE__).'\..\..' ));
} else define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../..' ));
define( 'DS', DIRECTORY_SEPARATOR );
// including the main joomla files
require_once ( JPATH_BASE.DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE.DS.'includes'.DS.'framework.php' );
// Creating an app instance
$app = JFactory::getApplication('site');
$app->initialise();
jimport( 'joomla.user.user' );
jimport( 'joomla.user.helper' );
$name = $_REQUEST['name'];
// You can apply validation on the name value here
// if all the validation is OK, we can then submit the name value to the database. For the demonstration purpose, I am just entering the name value in the users table, to show you how ajax works in joomla.
$db = JFactory::getDBO();
$query = "INSERT INTO #__users (name) VALUES ('$name')";
$db->setQuery($query);
$db->query();
echo '<div>The form field value has been submitted successfuly.</div>';
?>
Now, the above-mentioned Joomla PHP code would be a bit complex for a newcomer to Joomla, but for the sake of simplicity, I have given comments with each important code line. Copy and paste the above code in the ajax.php file. Your basic Ajax setup in Joomla is now complete.When you enter a valid text in the name field and press the “Save Name” button, you will get the following message, and the text in the name field will be saved in the “users” table.
As I have mentioned above, there are so many ways to implement ajax functionality in Joomla; even Motool’s approach is very popular, but I found this method very simple and easy to use.
If you found this article helpful, please don’t forget to share
thanks.
Hi Nohman,
I’m very new to Joomla and I really relied on your tutorial to learn about Ajax in Joomla.
I followed your instructions but unfortunately, it didn’t work.
I’m working on Joomla 3.9, so I changed the addScript lines like this
JHtml::script(Juri::base() . ‘http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js’);
JHtml::script(Juri::base() . ‘/components/com_djguitariste/js/ajax.js’);
In the console, I get this error message coming from the ajax.js file
ReferenceError: jQuery is not defined
I hope you can find a moment to have a look at my error and give me a hint.
Your help would be really apppreciated
Thanks in advance
Ossepove again
Corrected the js error like this :
JHtml::script(Juri::base() . ‘/components/com_djguitariste/js/jquery.js’);
instead of the download url for jquery
Also had to correct the create app instance like this to have it work :
$app =& JFactory::getApplication(‘site’);
Thanks a lot for your article
Thanks for going through the tutorial. I have declared the jQuery from the url, just to give you an understanding that you have to make the jQuery available for the script to work. Now its upto you, that you load it from the library or through the url, or it is already made available in template you are using. I will appreciate any questions you have regarding joomla.
Really nice article. I have read other articles on your site and always found them filling gaps in my knowledge.
Thank You for the good work!