Drupal 5: Drupal, AJAX, and jQuery made simple

Here’s a simple, minimal implementation of AJAX in Drupal using jQuery.

First create a menu item callback.

<?php
function MYMODULE_menu() {
  $items = array();
  $items[] = array(
    'path' => 'ajax',
    'title' => t('AJAX'),
    'type' => MENU_CALLBACK,
    'callback' => 'MYMODULE_callback_ajax',
    'access' => true,
  );
  return $items;
}
?>

Next create the callback function. To test the menu item and callback function, go to http://[YOURSITE]/ajax; you should get the text “wee!” without any theming.

<?php
function MYMODULE_callback_ajax() {
  echo 'wee!';
  die;
}
?>

Next create a page that has a button on it with an ID of “ajaxButton”. The following jQuery will add an onClick event to the button.

$(document).ready(function(){
  $('#ajaxButton').click(function(){
    $.ajax({
      type: 'GET',
      url: '/ajax',
      success: function(html){
        alert(html);
      }
    });
  });
});

The jQuery binds a function to the onClick event, with makes the Ajax call to the URL, which simply returns the text “wee!”, which is then echoed in a javascript alert box.

Updated: