Using AJAX in Drupal 7 outside of form API

There are many examples on how to use AJAX using form API, but I could not find a good example on how to use AJAX with markup. Here is a simple method.

To create an AJAX link in Drupal, outside of form API, we first need to add a menu item :

function MYMODULE_menu() {
$items = array();
$items['MYMODULE/ajax'] = array(
'page callback' => 'MYMODULE_ajax_callback',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['MYMODULE/ajax/%/%'] = array(
'page callback' => 'MYMODULE_ajax_callback',
'page arguments' => array(2, 3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}

Then, wherever you want to create a link, include the library :

// Add libraries
drupal_add_library('system', 'drupal.ajax');
drupal_add_library('system', 'jquery.form');

Create a link with the "use-ajax" class and a wrapper for the AJAX response. This is a dummy example, you must do this in an appropriate way of course :

// Output a link
l(t('AJAX'), 'MYMODULE/ajax/nojs/' . $some_argument, array('attributes' => array('class' => array('use-ajax'))));
// Output a wrapper
'<div id="MYMODULE-wrapper"></div>'

Finally, create your callback function :

function MYMODULE_ajax_callback($type = 'ajax', $some_argument) {
if ($type == 'ajax') {
$commands[] = ajax_command_replace('#MYMODULE-wrapper', 'Hey ! Some AJAX content !');
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);
}
else {
$output = t("This is some content delivered via a page load.");
return $output;
}
}

That's it !