Simple Drupal 7 AJAX Implementation

Boost the performance of your Drupal 7 website, improve usability and help with SEO by making content load via AJAX in just a few steps.

Drupal AJAX is a cinch to implement—as it should be since core is loaded with it. In just a few of steps I’ll show you how to use jQuery and Drupal’s hook_menu() function to quickly build a AJAX function to return anything from HTML to a JSON array.

Simple Drupal AJAX JSON Implementation

/**
 * Implementation of hook_menu().
 * @see https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7
 */
function moduleName_menu() {

  // Setup a URL to retrieve the JSON array.
  $items['node/%/moduleName/pageviews'] = array(
    'page callback'     => 'moduleName_get_pageviews',
    'page arguments'    => array(3),
    'type'              => MENU_CALLBACK,
    'access arguments'  => array('access content'),
    'delivery callback' => 'moduleName_ajax'
  );

  return $items;
}

/**
 * Returns the number of pageviews for a node ID.
 */
function moduleName_get_pageviews($nid) {

  // Some fancy function that returns pageviews.
  return fancyPageviews($nid);
}

/**
 * Renders a JSON array.
 */
function moduleName_ajax($pageviews) {

  // Tell the browser to expect JSON data.
  // @see https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_add_http_header/7
  drupal_add_http_header('Content-Type', 'application/json');

  // Output the JSON result
  // @see https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_output/7
  print drupal_json_output(array('pageviews', $pageviews));

  // Perform end-of-request tasks.
  // @see https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_page_footer/7
  drupal_page_footer();
}

With the above code (after clearing cache), visit yoursite.com/node/55/moduleName/pageviews to return a JSON array with the number of pageviews for node ID 55. More information on the hooks and functions used can be found below:

You can then use this URL and jQuery.getJSON() to return the data via AJAX.

;( function( $ ) {
  "use strict";

  // When document is ready...
  $( function() {

    // Get the JSON result.
    $.getJSON( "node/55/moduleName/pageviews", function( data ) {

      // Add the number of pageviews to the page.
      $( "#pageviews" ).text( data.pageviews );
    });
  });

})( jQuery );

Or if you need to pass data to the AJAX script:

;( function( $ ) {
  "use strict";

  // When ready...
  // @see http://www.benmarshall.me/drupal-behaviors/
  Drupal.behaviors.myModule = {

    // Arguments to pass to the AJAX script.
    vars arguments = { status: 'awesome' };

    // Send the arguments & return the JSON data.
    $.getJSON( "node/55/moduleName/pageviews", arguments ).done( function( data ) {

      // Add the number of pageviews to the page.
      $( "#pageviews" ).text( data.pageviews );
    });
  };

})( jQuery );

For more information on $.getJSON(), see http://api.jquery.com/jquery.getjson/.

You’ll also notice it’s using something called Drupal.behaviors. This is essentially a document ready for all content, including new content that get’s added to the page after load. For instance, if a modal is added to the page via AJAX and a function that’s already been initialized needs to run on the modal, normally you’d have to force event delegation. For a quick introduction to Drupal behaviors, see http://www.benmarshall.me/drupal-behaviors/.


A Closer Look

Like with everything in Drupal, there’s a number of ways to implement AJAX, but which is best? Let’s dive a little deeper into Drupal AJAX and take a look at how, why and when you can use this powerful feature.

AJAX outside the Form API is new in Drupal 7. It allows back and front-end developers the ability to leverage high performance and solid JSON and HTML responses. You can use this feature to update blocks, nodes, pages and any other element with better performance on the client and server-side vs. loading AHAH page fragments.

Drupal AJAX with jQuery

jQuery provides a few different AJAX commands, depending on your exact requirements. Here is the simplest Ajax call you can make with jQuery:

$( "#someDiv" ).load( url );

What this is saying is “Find the div with the id of ‘someDiv’ and load the html that you find at the location ‘url’ into this div”.

The jQuery utility functions below provide for the extra flexibility you need when dealing with data coming back from the server that needs to be parsed.

// https://api.jquery.com/jquery.get/
$.get( url, parameters, callback );

// http://api.jquery.com/jquery.post/
$.post( url, parameters, callback );

// http://api.jquery.com/jquery.ajax/
$.ajax( options, settings );

// http://api.jquery.com/jquery.getjson/
$.getJSON( url, data, success );

// http://api.jquery.com/load/
$.load( url, data, complete )

The only difference between $.get and $.post is the HTTP request method used to send your parameters (an array passed as the second argument) to the server. Very often in Drupal, you won’t need to send any parameters because the url you will be calling will be a menu callback you have set up as, for example, ‘ajax/get/node_details’ taking one argument, ‘nid’ and so you would simply make the call to ‘ajax/get/node_details/123’ and not need to send your nid parameter as a parameter in the second argument.


Additional Resources:

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

Leave a Reply

Your email address will not be published. Required fields are marked *