Sunday, June 08, 2008

Auto refresh div using jQuery and 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 <div> 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:

    <div class="autorefresh">
    Put something here. It will get updated at a set interval.
    <div>


  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.



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.

11 comments:

Nursultan said...

Hello!

This very interesting, but I, as a web-development noob, have trouble implementing your example.
Where exactly do I put each snippet of code?
I guess the menu function goes into template.php while scripts go to the page header in page.tpl.php, but I could not make it work this way.
Thank you in advance!

Todd said...

To understand this example you must first understand how to develop a Drupal module. To get started with module development I would check out the module development guide on the Drupal site (http://drupal.org/node/508). Module development in Drupal can be overwhelming to a new web developer so I would highly recommend picking up a reference text - my favorite is Pro Drupal Development (http://www.drupalbook.com/).

Unknown said...

thank you for this page!!! I got this working in Drupal 6 with changes, but using yr gerneral ideas. this page really helped alot in learning drupal and jquery. thanks again --- of mention in the drupal 6 fixes =

[[in the module itself]]

function jrefresh_menu() {
$items['jrefresh.json'] = array(
'title' => 'jRefresh AJAX gateway',
'page callback' => 'jrefresh_update',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}


function jrefresh_update() {
$html = _get_datadump();
return drupal_json(array('html' => $html));
exit();


[[part of the js code in the .js file]]

function autoupdate() { $.getJSON(Drupal.settings.jrefresh.json_url, function(json) {
$("div.autorefresh").hide().fadeIn("slow").html(json['html']);
}
)};

Symmetry said...

Hello, I'm new in drupal. Can You explaing "Create a menu function in Drupal"?

Pavani Akella said...

Hi,
I was building the drupal module from the customer service chat script I wrote in php
As part of it..I have created 2 pages one for customers and one for staff where staff can login and redirected to a page with a list of customers waiting which needs to be updated every x secs..and customer side they login and transferred to a chat window with a wait message and as it is chat it needs to updates every 2 sec and there should be a text box at the bottom of the page and the chat div need to be updated...


so I need help to update a chat div of a drupal page to get updated and the other is form element text box.This page is also created in this module only..

Please help me..

Regards,
Pavani

heas2 said...

hi

is this actually working ive tried it over and over again but it doesnt refresh.

can yo uplease upload a working module if it does work.

Thanks

Unknown said...

really u have posted very informative ideas thanks for sharing these information...
Drupal Development is getting more reputation because all the small, huge and method variety companies have chosen it as a open source for their web presence.

Unknown said...

it was nice post you distributed with examples thanks for it ..The best advantage of the drupal is that it can be customized to meet the user’s requirements.With
Drupal Development one can customize the visual appearance of the website.

Unknown said...
This comment has been removed by the author.
Unknown said...

Hi Todd,

Many thanks for this article that really helped me.
As a sign of gratitude, I thought I could post a working example for Drupal 7 (I wasted some time to solve a few issues and there are minor changes with regards to your version :

(function($){

$(document).ready(function(){
setInterval("Drupal.my_module.autoupdate()", 60000);
});

/**
* Helper functions used my_module.
*/
Drupal.my_module = {

autoupdate: function(){
$.ajax(
{
type: "POST",
url: Drupal.settings.basePath + "/block_update/update/",
cache: false,
success: function(data) {
var result = $.parseJSON(data);
$("div#mydiv").fadeIn("slow").html(result['html']);
}
});
}

};

})(jQuery);



Millionmakerscare said...


Hey Nice Blog!!
Thanks For Sharing!!! Nice blog & Wonderfull post. Its really helpful for me, waiting for a more new post. Keep on posting!


web development company
software development company
app development company