Difference between revisions of "Adding AJAX to your component"

From Joomla! Documentation

(Add version tag and mark needs review)
Line 1: Line 1:
To add ajax to your component:
To add ajax to your component:

Revision as of 03:11, 22 April 2013

Replacement filing cabinet.png
This Namespace has been archived - Please Do Not Edit or Create Pages in this namespace. Pages contain information for a Joomla! version which is no longer supported. It exists only as a historical reference, will not be improved and its content may be incomplete.
This Page Needs Your Help

This page is tagged because it NEEDS REVIEW. You can help the Joomla! Documentation Wiki by contributing to it.
More pages that need help similar to this one are here. NOTE-If you feel the need is satistified, please remove this notice.

To add ajax to your component:

Phase 1

1- Make the necessary javascript ajax functionality in your default.php (or other template in components/com_xxx/views/yyy/tmpl/)

<script language='javascript'>   
function ajxGetCitys(country_id){
    var xhr = getXhr();
    // On défini ce qu'on va faire quand on aura la réponse
    xhr.onreadystatechange = function(){
      // On ne fait quelque chose que si on a tout reçu et que le serveur est ok
      if(xhr.readyState == 4 && xhr.status == 200){
          var city=document.getElementById('city');
          try //Internet Explorer
            xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
          try //Firefox, Mozilla, Opera, etc.
              parser=new DOMParser();
          catch(e) {alert(e.message)}
          var options =xmlDoc.getElementsByTagName('options').item(0);
          for (i=0; i < options.childNodes.length; i++){          
            var newoption=document.createElement("option");
            var myoption=options.childNodes[i];
            var newtext=document.createTextNode(myoption.childNodes[0].nodeValue);

Phase 2

2- in the controller.php add new function (or task)like listcity ,see the following example:


function listcity()
     global $mainframe;
     $country_id=JRequest::getVar( 'country_id');
     $model = $this->getModel('register');
     $states = $model->getStates($country_id);
     $return = "<?xml version=\"1.0\" encoding=\"utf8\" ?>";
     $return .= "<options>";
     $return .= "<option id='0'>".JText::_( '---Select city---' )."</option>";
     if(is_array($states)) {
        foreach ($states as $state) {
         	$return .="<option id='".$state->state_id."'>".JText::_($state->state_name)."</option>";
      $return .= "</options>";
      echo $return;      

3- Here i have a method getStates($country_id) in the register model to extract the list countries from my bdd ,you can do it another way and adapt to your needs .Good luck