For this example, we will use jQuery.ajax() to display the node via Ajax. jQuery.Ajax() expects a url and a settings object containing key/value pair that configure the request. For the url part, we will utilize drupal_hook_menu()'s page callback value to respond to our ajax request. First off, we will include the javascript file that will make the ajax request.
1. Include the javascript file and setting
/**
* Implements hook_init
* @file moduleAjax.module
*/
function moduleAjax_init() {
global $base_path;
// Include the javascript file, from which we will make the ajax request from.
drupal_add_js(drupal_get_path('module', 'moduleAjax') . '/js/ajax.js');
// Set the base_path variable to be accessible from javascript
drupal_add_js(
array('sitewide' => array(
'base_path' => $base_path,
)), 'setting');
}
2. Register the menu router for ajax callback
/**
* Implements hook_menu().
*/
function moduleAjax_menu() {
$items['ajax/node-view/%'] = array(
'page callback' => '_ajax_node_load',
'page arguments' => array(2),
'access callback' => 'user_access',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
3. Implement Page Callback for Ajax Path
/**
* Implements _ajax_node_load
*/
function _ajax_node_load($nid) {
$node = node_load($nid);
//pass rendered node to ajax.
$output = drupal_render(node_view($node, 'full'));
drupal_json_output($output);
}
4. Implement jQuery.ajax() on Our ajax.js File
/*
* @file moduleAjax.js
*/
(function($) {
Drupal.behaviors.modAjax = {
attach: function(context, settings) {
//Set listener to a button, with callback function making the ajax request
$("a#ajaxBtn").click(function(){
$url = Drupal.settings.sitewide.base_path + 'node-view/' + 1; //where 1 is the nid that will be passed into _ajax_node_load
$.ajax({
url:$url,
type:'POST',
cache:true,
start: function(data) { },
success: function(data) {
$("#zone-content").html('').append(data);
},
error: function(data) {
$("#zone-content").html(data);
alert("ERROR");
},
complete: function(data){ }
}); //end of $.ajax
}); //end of click event
}, //end of attach property
}; //end of Drupal.behaviors.modAjax
})(jQuery);