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.ajax process flow

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.

4 Comments

Leave a Reply to Pranay Cancel reply

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com