Attaching AJAX events to non-form page elements in Drupal

Making AJAX request in Drupal using the form API is real nice and simple

Attaching AJAX events to non-form page elements in Drupal

Making AJAX request in Drupal using the form API is real nice and simple, but did you know you can also attach AJAX actions to normal page elements easily as well? In this quick tutorial I’ll show you how to easily do just that. It also provides support for browsers that don't support Javascript.

The code below is pretty standard Drupal code. It sets up a couple of menu items, and a couple of pages. One page displays a link “Click to load” and upon clicking on that link you are taken to a page that has a list of links to some common search engines. Pretty straight forward.

 <?php
 /**
  * Implements hook_menu().
  */
 function ajax_example_menu() {
   $items = array();
   $items['ajax_example'] = array(
     'title' => 'AJAX example',
     'page callback' => 'ajax_axample_landing_page',
     'access arguments' => array('access content'),
     'type' => MENU_NORMAL_ITEM,
   );
   $items['ajax_example/target'] = array(
     'title' => 'AJAX target content',
     'page callback' => 'ajax_example_target_page',
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );
   return $items;
 }
 
 /**
  * Page callback for returning content to display on the
  * example page.
  */
 function ajax_axample_landing_page() {
   return l('Click to load', 'ajax_example/target');
 }
 
 /**
  * This is the target page, We want to load this using AJAX
  */
 function ajax_example_target_page() {
   $links = array(
     'bing' => array(
       'title' => 'Bing',
       'href' => 'http://www.bing.com'
     ),
     'gogle' => array(
       'title' => 'Google',
       'href' => 'http://www.google.com'
     ),
     'yahoo' => array(
       'title' => 'Yahoo',
       'href' => 'http://www.yahoo.com'
     ),
   );
   return theme('links', array('links' => $links));
 }
 ?>

Now, what if I wanted to load the search engine links page via AJAX, and append them to the current page? It’s actually really simple, and it doesn’t involve much additional code either. Let's take a look. All I need to do is make a few changes. The first thing we want to do is alter the landing page code, which will make it look like this.

 <?php
 /**
  * Page callback for returning content to display on the
  * example page.
  */
 function ajax_axample_landing_page() {
   drupal_add_js('misc/ajax.js');
   return l(t('Click to load')  , 'ajax_example/target/nojs/',
     array('attributes' => array('class' => array('use-ajax')))
   ) . '<div id="target"></div>';
 }
 ?>

The first thing I have done here is added misc/ajax.js to the page. This will ensure that the library is included.

Secondly I have added a /nojs/ to the end of the link URI. This is a special property that the AJAX library uses when sending requests, it will be replaced with /ajax/ when making AJAX requests. This value is also passed to the page callback so we know how the request was made. We'll look at that function in a second.

You'll see I have also added a CSS class to the link use-ajax. This tells Drupal to use AJAX. When this class is added, Drupal will request the URL of the link with AJAX.

I tacked on a <div id="target"></div> after the link. This is where we want to put the results from our AJAX request.

We have to make some changes to the page callback we are requesting too. Let's now take a look those changes.

 <?php
 /**
  * This is the target page, We want to load this using AJAX
  */
 function ajax_example_target_page($type = 'ajax') {
   $links = array(
     'bing' => array(
       'title' => 'Bing',
       'href' => 'http://www.bing.com'
     ),
     'gogle' => array(
       'title' => 'Google',
       'href' => 'http://www.google.com'
     ),
     'yahoo' => array(
       'title' => 'Yahoo',
       'href' => 'http://www.yahoo.com'
     ),
   );
 
   $content = theme('links', array('links' => $links));
   if ($type != 'ajax') {
     return $content;
   }
 
   $commands = array();
   $commands[] = ajax_command_replace("#target", $content);
   ajax_deliver(array('#type' => 'ajax', '#commands' => $commands));
 }
 ?>

A few things have changed here, first up the function declaration now has an optional parameter, $type = 'ajax' this parameter is passed to the function by the Drupal AJAX library, its value is nojs when javascript is not available.

NOTE: if you are using 'page arguments' in your menu definition, then the $type variable will be last.

I have assigned the content to the $content variable and if the request isn't AJAX based we simply just return it. This allows those browsers that don't support Javascript like screen readers etc to still view the content that is linked to.

After that you'll see that I build a commands array and add the result of ajax_command_replace('#target', $content) to it. What I am doing here is telling Drupal that I want to run the AJAX replace command, #target is the css selector of what I want to replace and $content contains the HTML I want to replace it with.

At this point I could also add any number of the pre-defined Drupal AJAX commands to the commands array, or even some custom commands I'd defined myself. However for the purpose of this tutorial, we'll keep it simple

The last thing we do is make a call to ajax_deliver(). This renders the response as a valid JSON/AJAX response. From that point the Drupal AJAX library handles the rest.

Now when we click the link we get the Drupal AJAX spinner and then the page is updated with the list of search engines. It’s as easy as that.