Search code examples
jqueryjsonjgrowl

Dynamic notifications using jQuery


I'm currently building a homepage for our staff which is to be set as the homepage in their browser. I'm currently building the facility whereby nominated members of staff can send notifications to all staff. These will popup on their home page without the need for them to refresh the page.

I've currently got the code below which worked fine for 1 notification, but there may be more than 1 at a time waiting to be shown. I've switched to outputting json but I'm not sure how to modify my code to consume it.

I'm using the PeriodicalUpdater and jGrowl plugins to get this functionality, if there's better alternatives then feel free to sugget them.

    $.PeriodicalUpdater({
        url: 'getNotifications.aspx',
        maxTimeout: 6000,
        type: 'json'
    },
    function(data) {
        var message = data;
        if (message != '') {
            $.jGrowl(message, { sticky: true });
        }
    });

As an additional piece of functionality, would it be possible to store in a cookie when a user has closed a notification so they don't see it again?

Thanks.


OK, I've updated the code so that it's now;

        $(document).ready(function() {
        var alreadyGrowled = new Array();

        var growlCheckNew = function() {
            $.getJSON('getNotifications.aspx', function(data) {
                $(data).each(function(entryIndex,entry) {
                    var newMessage = true;
                    $(alreadyGrowled).each(function(index,msg_id) {
                        if (entry['ID'] == msg_id) {
                            newMessage = false;
                        }
                    });

                    if (newMessage == true) {
                        $.jGrowl(entry['Message'], {
                            sticky: true,
                            header: entry['Title'],
                            beforeClose: function(e,m) {
                                alert('About to close this message');
                            }
                        });
                    }
                    alreadyGrowled.push(entry['ID']);
                });
            });
        }

        growlCheckNew();

        var msgTimer = setInterval(growlCheckNew, 1000);

    });

However, my alerts not firing when I close a growl notification?! I've got that in there to check it works before putting some code in to save it to a cookie. Does this look about right?


Solution

  • you can output all the messages as a list in the JSON output and simply iterate over the message list in javascript.

    JSON output:

    {
        messages:['msg1', 'msg2', 'msg3']
    }
    

    javascript:

    $.PeriodicalUpdater({
        url: 'getNotifications.aspx',
        maxTimeout: 6000,
        type: 'json'
    },
    function(data) {
        for(message in data.messages) {
            $.jGrowl(message, { sticky: true });
        }
    });