AJAX is a great way to add dynamic content to your Drupal website. Doing so though, requires a few steps.

First, in order to add Ajax to a Drupal page, we must add the Drupal AJAX library and a new JS file to the page. This can be done through a hook_page_alter() or hook_block_view(), for example.


function MODULE_NAME_page_alter() {
  drupal_add_library('system', 'drupal.ajax');
  drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . '/MODULE_NAME.js');
}

Next, one must add two new menu items, one for the AJAX callback and one as a non-JavaScript fallback. Hook_menu() is used for this as it will tell Drupal which function to call when directed to the specified URL.


function MODULE_NAME_menu() {
  $items = array();
  $items['path/ajax'] = array(
    'title' => 'My custom ajax callback',
    'page callback' => 'MODULE_NAME_ajax_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['path/nojs'] = array(
    'title' => 'My custom non-javascript callback',
    'page callback' => 'MODULE_NAME_nojs_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

Then, one must add the two callback functions. In the AJAX callback, an array of Drupal AJAX commands is returned.


function MODULE_NAME_ajax_callback() {
  $ajax_commands = array();
  $ajax_commands[] = ajax_command_replace('#ajax-link', 'AJAX commands run.');
  ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));
}

function MODULE_NAME_nojs_callback() {
  return;
}

Lastly, one must create the new javascript file with the AJAX call.


(function ($) {
  Drupal.behaviors.my_custom_module = {
    attach: function(context, settings) {
      var $ajaxLink = $('#ajax-link', context);
      new Drupal.ajax('#ajax-link', $ajaxLink, {
          url: $ajaxLink.attr('href'),
          settings: {},
          event: 'click tap'
      });
    }
  }
})(jQuery);


Additional resources: