AJAX Using The JQuery Javascript Library

Drupal 6, like Drupal 5 before it, has the JQuery javascript library built-in. Among other things the library makes it child's play to make AJAX requests.

$(document).ready(function() {
  $('a#aCSS04').click(function() {
    if(!$('div#CSS04').length) {
      //add the div to the dom
      $(this).after('<div id="CSS04"></div>');
    } 
    if(!$('div#CSS04').hasClass('loaded')) {
      //load the data
      $.get('http://scripts.dev/jquery/mycode.php', 
        {funcName: 'cssGetCode', param: 'CSS04' },
        function(data){
          //callback function - called when data loaded successfully
          $('div#CSS04').html(data).addClass('loaded');
        }
      );
     } else {
       //data already loaded - toggle view
       $('div#CSS04').toggle('slow'); 
     };
     //stop default anchor behaviour 
     return false;  
   });  
});

The relevant HTML basically looks like <a href="#" id="aCSS04">Show/Hide code</a> This automatically adds the onclick handler to the anchor element with id="aCSS04". Clicking on this will result in one of two actions:

  • if the div element with id="CSS04" has not been initialised i.e. does not have the CSS class 'loaded', an AJAX GET call is made to the server, the data returned is then added to the div element. A CSS class 'loaded' is also added to the element to show the data has been loaded. Here I amusing the get method, but other methods are available. You can add custom data to the AJAX call. In this case, the name of the function to be called at the server end, and the parameter to be passed to this function are added to the call. These can be accessed on the server-side as normal GET parameters.
  • if the div element with id="CSS04" has been initialised i.e. has CSS class 'loaded', then the div's visibility is toggled between display and no display. The toggle() method does what it says on the tin i.e. toggles the element visibility. The parameter to this function tells it what effect to use.

That's it - you can fetch data and populate DOM elements that you add on the fly.

Back to top