I have a notification bar with a counter, it actually prints the user's "notifications" field value (if it's greater than 0):

<div id=container>
<a href="#" class="activity_link">Activity</a>
global $user;
$user_fields = user_load($user->uid);
$user_notifications = $user_fields->field_notifications['und']['0']['value'];
if ($user_notifications > 0) {
echo '<div class=blob>'.$user_notifications.'</div>';
echo '<div style="display:none">'.flag_create_link('unmark_notifications', $user->uid).'</div>';

And a jQuery function that resets the value to 0 on click:

    (function ($) {
      Drupal.behaviors.scriptjs =  {
        attach: function(context, settings) {

        $('.activity_link').click(function() {
        $('.flag-unmark-notifications .flag-action').click();
        $('.flag-unmark-notifications .unflag-action').click();

The problem is that when a new notification is received you need to refresh the page to see it.

What I've thought to do is to pass the user's "notifications" field to jQuery and update accordingly..

Is this the best way to do it or should I think about using Node JS?

How would you listen for a field value change event and then refresh the counter?

3 Answers 3


You can use Block Refresh module. Put the notification's content in a block and using this module refresh block in some interval of time. In block template write your own condition or logic.


You could create 2 menu items;

  1. check the notifications, json delivery (let's call it menu item 1)
  2. render the container. custom html (let's call it menu item 2)

On your JS file, you could use a SetInterval ajax call to check your menu items 1 (check the json data) and then if your condition match, use jQuery.load to get the fragment you want on the 2nd menu item or the whole page to replace the current block.

For the notification menu item 1, I recommend you to use High-performance JavaScript callback handler to optimise the callback.


An overview of tasks what you need to do :

  • Add a js file to your module, or wherever your notifications update logic is (strictly not in the .tpl file as its against the standards, but if you really want to add here - instead add it in the tpl's preprocess function)
  • In this js file, fire an ajax request $.ajax() looking out for notifications count (this will actually be a Drupal menu callback doing the querying job in the backend)
  • If the query results reveal > 0 notifications, return the number back to your js file (in the $.ajax's .success() callback)
  • The .success() should update only the notification counter by using its DOM identifier (.blob in your case) - use html(response.data) to update

You have now a fully functional Ajaxified notification counter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.