Simple Drupal 7 AJAX Implementation

Typical Read
5 minutes
Share on facebook
Share on twitter
Share on linkedin
Sponsored Advertisement
Need a website or help with an existing one? Get a free quote today.

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
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!
  drupal_add_http_header('Content-Type', 'application/json');

  // Output the JSON result
  // @see!
  print drupal_json_output(array('pageviews', $pageviews));

  // Perform end-of-request tasks.
  // @see!

With the above code (after clearing cache), visit 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
  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

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

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.

$.get( url, parameters, callback );

$.post( url, parameters, callback );

$.ajax( options, settings );

$.getJSON( url, data, success );

$.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:

Related Articles

Leave a Reply

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

All comments posted on 'Simple Drupal 7 AJAX Implementation' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.