J1.5

Difference between revisions of "Ajax client code using MooTools"

From Joomla! Documentation

(No need to declare a CDATA block, this will be handled by JDocument all by itself.)
(4 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 +
{{notice|This article applies to Joomla! 1.5 only as Joomla! 1.6 ships with a later version of MooTools which has a different way
 +
of handling Ajax requests.}}
 +
 
In a typical Ajax application you will want to pull some data from a server, which could be your own Joomla site or a remote web service, and update some element on the web page with the data returned by the server.  There are three elements to a typical Ajax implementation:
 
In a typical Ajax application you will want to pull some data from a server, which could be your own Joomla site or a remote web service, and update some element on the web page with the data returned by the server.  There are three elements to a typical Ajax implementation:
 
* An HTML element whose change of state will trigger the Ajax request.
 
* An HTML element whose change of state will trigger the Ajax request.
Line 84: Line 87:
 
The following is a more complete example of an Ajax function which receives data from the server in JSON format, decodes it, then pushes data from the response into <tt>ajax-container</tt>.
 
The following is a more complete example of an Ajax function which receives data from the server in JSON format, decodes it, then pushes data from the response into <tt>ajax-container</tt>.
 
<source lang="javascript">
 
<source lang="javascript">
window.addEvent( 'domready', function() {
+
window.addEvent('domready',function() {
 
 
$('drop-down').addEvent( 'change', function() {
 
 
 
$('ajax-container').empty().addClass('ajax-loading');
 
  
var a = new Ajax( {$url}, {
+
    $('drop-down').addEvent('change',function(){
method: 'get',
 
onComplete: function( response ) {
 
var resp = Json.evaluate( response );
 
  
// Other code to execute when the request completes.
+
          $('ajax-container').empty().addClass('ajax-loading');
  
$('ajax-container').removeClass('ajax-loading').setHTML( output );
+
          var a = new Ajax({$url},{
 +
              method:'get',
 +
              onComplete:function(response){
 +
                    var resp=Json.evaluate(response);
  
}
+
                    // Other code to execute when the request completes.
}).request();
+
                    $('ajax-container').removeClass('ajax-loading').setHTML(output);
});
+
              }
 +
          }).request();
 +
    });
 
});
 
});
 
</source>
 
</source>
 
Notice that in this example there is also some code to add, and subsequently remove, an <tt>ajax-loading</tt> CSS class from the <tt>ajax-container</tt> element.  Typically, the presence of this class will cause a "spinner" graphic element to be loaded as a background image to make the user aware that the system is still alive.
 
Notice that in this example there is also some code to add, and subsequently remove, an <tt>ajax-loading</tt> CSS class from the <tt>ajax-container</tt> element.  Typically, the presence of this class will cause a "spinner" graphic element to be loaded as a background image to make the user aware that the system is still alive.
 
<noinclude>[[Category:Development]][[Category:Topics]]</noinclude>
 
<noinclude>[[Category:Development]][[Category:Topics]]</noinclude>

Revision as of 18:43, 5 November 2011

The "J1.5" namespace is an archived namespace. This page contains information for a Joomla! version which is no longer supported. It exists only as a historical reference, it will not be improved and its content may be incomplete and/or contain broken links.

Info non-talk.png
General Information

This article applies to Joomla! 1.5 only as Joomla! 1.6 ships with a later version of MooTools which has a different way of handling Ajax requests.

In a typical Ajax application you will want to pull some data from a server, which could be your own Joomla site or a remote web service, and update some element on the web page with the data returned by the server. There are three elements to a typical Ajax implementation:

  • An HTML element whose change of state will trigger the Ajax request.
  • Another HTML element where the response data will be placed. Often this will show an "Ajax loading" icon or message while the response from the server is being awaited.
  • The Ajax JavaScript code itself.

Starting with the first of these, you need to identify the element on the page that will trigger the Ajax request. The element needs to be identified by a unique id attribute. For example, suppose you have a drop-down select box on your page and you want to do an Ajax request whenever the user changes the item selected. Then you must ensure that the select element has a unique id attribute like this:

<select name="drop-down" id="drop-down">
        <option value="1">Item 1</option>
        <option value="2">Item 2</option>
        <option value="3">Item 3</option>
</select>

You can generate this select list programmatically using the JHTML class like this:

<?php
$options = array();
$options[] = JHTML::_( 'select.option', '1', 'Item 1' );
$options[] = JHTML::_( 'select.option', '2', 'Item 2' );
$options[] = JHTML::_( 'select.option', '3', 'Item 3' );
echo JHTML::_( 'select.genericlist', $options, 'drop-down' );

Secondly, you need to add an HTML element that will hold the output from the Ajax call. This could be a suitably-placed DIV, which must also have a unique id attribute, like this:

<div id="ajax-container"></div>

You can, of course, use the id in a selector to style the output using CSS.

Thirdly, you need to add the JavaScript code that will make the Ajax request and place the response into the screen output. You generally don't need to be concerned about loading MooTools itself as this is done automatically for you by Joomla, but sometimes you need to do this manually by adding the following code:

<?php
JHTML::_( 'behavior.mootools' );

There are many ways to add JavaScript code to the output from Joomla. One way, which avoids complex quoting, is to use the PHP "heredoc" syntax (see [1] for more details) like this:

<?php
$ajax = <<<EOD
Your JavaScript code goes here.
EOD;

$doc = & JFactory::getDocument();
$doc->addScriptDeclaration( $ajax );

You can embed PHP variables in the heredoc text by surrounding them with braces, like this:

<?php
$ajax = <<<EOD
This is some JavaScript code with {$this->embedded} PHP variable in it.
EOD;

$doc = & JFactory::getDocument();
$doc->addScriptDeclaration( $ajax );

The JavaScript code must add an event handler to the element that will trigger the Ajax call. This is done in MooTools using the following call:

window.addEvent( 'domready', function() {

	$('drop-down').addEvent( 'change', <function-declaration> );

});

where <function-declaration> is the JavaScript code that is to be called when the state of the element identified as drop-down is changed. Notice that you should always delay the call to addEvent until the DOM is ready following a page load. This is done by telling window.addEvent to hang the Ajax addEvent function onto the onDomReady event.

You don't have to hang the Ajax call on the onChange event; for example, you could use onClick as the trigger.

The <function-declaration> that you will add will be an instantiation of the MooTools Ajax class, looking something like this:

var a = new Ajax( {$url}, {
	method: 'get',
	update: $('ajax-container')
}).request();

where {$url} is a PHP variable containing the URL for the Ajax request. In this example the update argument has been used to copy the entire response from the server into the ajax-container element. This is quick and convenient, but very often you will want to process the response in some way before showing it to the user. Commonly, the response is JSON-encoded and you must decode the response and format it appropriately before updating ajax-container. To do this, use the onComplete argument to the Ajax object rather than the update argument.

var a = new Ajax( {$url}, {
	method: 'get',
	onComplete: <completion-function>
}).request();

where <completion-function> is a JavaScript function that will be called when a response from the remote server is received. Typically, this function will process the raw data from the server before pushing it into the ajax-container element.

The following is a more complete example of an Ajax function which receives data from the server in JSON format, decodes it, then pushes data from the response into ajax-container.

window.addEvent('domready',function() {

     $('drop-down').addEvent('change',function(){

          $('ajax-container').empty().addClass('ajax-loading');

          var a = new Ajax({$url},{
               method:'get',
               onComplete:function(response){
                    var resp=Json.evaluate(response);

                    // Other code to execute when the request completes.
                    $('ajax-container').removeClass('ajax-loading').setHTML(output);
               }
          }).request();
     });
});

Notice that in this example there is also some code to add, and subsequently remove, an ajax-loading CSS class from the ajax-container element. Typically, the presence of this class will cause a "spinner" graphic element to be loaded as a background image to make the user aware that the system is still alive.