Usually calling Drupal.attachBehaviors makes the new elements added to the DOM reflect changes that happened to the old elements as desired. This, however, is not always enough. Sometimes, we need more control, it is easy to alter the response if you created the AJAX call yourself (using jQuery $.ajax() for example), but what if you are building on others' work..
Here is our case here :
You have installed the Views module on Drupal 6.
You have a view using AJAX.
You need to change some properties in the response of the AJAX call before it is displayed.
The Idea is to use the hook_drupal_alter() that is used by Views module to make other modules able to change AJAX request/response options and parameters.
So .. We will use it to add a Javascript callback to be executed on the response before it is displayed.
<?php
/**
** Implementation of hook_ajax_data_alter().
*/
function modulename_ajax_data_alter(&$object, $module, $view) {
global $views_ajax_form_js_settings;
if (!empty($views_ajax_form_js_settings)) {
$object->__callbacks = array_merge(array('Drupal.themeOrModuleName.functionName'), $object->__callbacks);
}
}
?>
Drupal.themeOrModuleName = {};
Drupal.themeOrModuleName.functionName = function(target,response) {
// we use $().html which gets the inner HTML and so
//.. the top div tag is not encluded, so we save it here
var firstDiv=response.display.slice(0,response.display.indexOf('>')+1);
// do all changes that we need to the loaded context then
//.. add the first div tag so the new context = firstDiv+$().html+'</div>'
response.display = firstDiv+$(response.display).each(function() {
}).html()+'</div>';
}
Replace themeOrModuleName and functionName as described in the above step.
This code can be added to :
drupal_add_js($code,'inline');
where $code contains the code aboveOr
I needed this technique with jQuery animations on dynamic elements (elements being replaced/changed with AJAX) calls. Please, tell me if you find this helpful or if it didn't work for you.
Comments
Drupal 7 and Views 3 replaces object with commands
This was really helpful and get things rolling to find out that in Drupal 7 that
&$object
is now commands instead - an array of framework commands (see http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax_commands/7).