Drupal 6 AJAX auto callback

webadmin's picture
Drupal

Recently I had to figure out how to automatically refresh a Drupal block every 5 minutes. The concept is simple enough but since I am new to jQuery (javascript in general really) and Drupal it was difficult for me to find a straight forward example. What follows is step-by-step example of how I solved the problem...

1. Wrap the content you want to refresh in a tag and give it a meaningful class name or ID (e.g., auto--refresh). The class name (or ID) is arbitrary as you will see in later steps.

For example:

Put something here. It will get updated at a set interval.

2. Create a menu function in Drupal to map the AJAX calback:


function blockupdate_menu() {
$items = array();
$items[] = array(
'path' => 'blockupdate/update',
'callback' => 'block_update',
'type' => MENU_CALLBACK,
'access' => TRUE,
);
return $items;
}

3. Implement the function that assembles the data to get sent back to the browser:


function block_update() {
//The get_data() function is generic here
//Use this function to get the updated data for display
$html = get_data();
print drupal_to_js(array('html' => $html));
// The exit() call is critical!
exit();
}

4. Implement the client side callback function in jQuery:


function autoupdate() {
$.ajax(
{
type:"POST",
url: "blockupdate/update",
cache: false,
success: function(data) {
var result = Drupal.parseJson(data);
$("div.autorefresh").fadeIn("slow").html(result['html']);
}
});
}

5. Use the setInterval Javascript function to perform the auto refresh:


if( Drupal.jsEnabled ) {
$(document).ready(function() {
setInterval("autoupdate()", 5 * 60000);
});
}

Note that the first parameter is the jQuery callback function and the second parameter is the time that will elapse in between a refresh, in milliseconds.


PS : this script work on code, if you have understand enough for building a Drupal Modules.

That's all there is to it really! To debug the new functionality make sure you have Firebug extension installed in Firefox and watch the traffic do a full roundtrip with updated content. It's also a good idea to set your interval to no more than a few seconds at first to ensure everything is working properly. Don't forget to read my last post on some of the lessons I learned while exploring jQuery inside of Drupal.