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 that how a typical ajax requests works.

 How a typical ajax request works

        Without the usage of ajax,  interaction between the user and the web server, hosting the web page occurs in lot of different steps. While through ajax,  interaction becomes more responsive as the user gets the response back, without even a click of a button. The figure below illustrates the process of a typical request, through ajax.

       This is a 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 occuring in the background and the user directly interacts with the web page if all the authentication is ok.  All this process occurs without any page refresh and asynchronously.

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 = &amp;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 =&amp; 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 new comer 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. Now here, all your basic ajax setup in joomla is complete. When you will enter a valid text in the name field and press the "Save Name" button, you will get the following message and the name field text will be saved in "users" table.

ajax response

         As I have mentioned above that there are so many ways to implement ajax functionality in joomla, even motools approach is very popular, but I found this method very much simple and easy to use.

          If you found this article helpful, please don't forget to share
          thanks.

Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google PlusSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn

Related Articles

You have no rights to post comments

Enjoy best web development services at an affordable price. Looking forward to build a good relationship and serve you better...

Copyright © 2017. All rights reserved.