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
[php]
/**
* 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();
}
[/php]
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:
hook_menu()
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7
Define menu items and page callbacks. This hook enables modules to register paths in order to define how URL requests are handled.drupal_add_http_header( $name, $value, $append = FALSE )
https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_add_http_header/7
Sets an HTTP response header for the current page. Note: When sending a Content-Type header, always include a ‘charset’ type, too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).drupal_json_output()
https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_output/7
Returns data in JSON format. This function should be used for JavaScript callback functions returning data in JSON format. It sets the header for JavaScript output.drupal_page_footer()
https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_page_footer/7
Performs end-of-request tasks. This function sets the page cache if appropriate, and allows modules to react to the closing of the page by callinghook_exit()
.
You can then use this URL and jQuery.getJSON()
to return the data via AJAX.
[js]
;( 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 );
[/js]
Or if you need to pass data to the AJAX script:
[js]
;( function( $ ) {
"use strict";
// When ready…
// @see https://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 );
[/js]
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 https://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:
[js]$( "#someDiv" ).load( url );[/js]
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.
[js]
// 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 )
[/js]
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.
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.