0

I made a notification system. I wish I could, via Ajax, to call the function that allows me to display the number of unread notifications. There is the possibility, by browsing the website, you call the function every 10 seconds, for example, automatically. Thanks for your help. For now I have this code:

function notifications()
{
    $.get("//localhost/laravel/public/index.php/new_notifications", 
    function(data)
    { 
        data_parsed = JSON.parse(data);

        if(data_parsed.length > 0)
        {
            //code
        }
    });
}
Francesco
  • 27
  • 2
  • 10

2 Answers2

1

if you want to call a function every few seconds, using javascript's set Interval should do:

window.setInterval(function(){
  /// call your function here
}, 5000);

Source

This function will loop/be called every 5 seconds.

setInterval is a standard JavaScript function, not part of jQuery. You call it with a function to execute and a period in milliseconds:

Here's how it might look:

setInterval(function(){
    $.ajax({ url: "server", success: function(data){
        //Update your dashboard gauge
        salesGauge.setValue(data.value);
    }, dataType: "json"});
}, 10000);

Source

Community
  • 1
  • 1
jbutler483
  • 24,074
  • 9
  • 92
  • 145
  • plus one since you noted your sources as well. I also liked the definition of setInterval, because I didn't actually know that. :s –  Nov 24 '14 at 15:49
0

Let's say you have a div somewhere that contains that information.

<div id="unreadNotification" ></div>

Refresh that div in your ajax call.

function notifications()
{
    $.get("//localhost/laravel/public/index.php/new_notifications", 
    function(data)
    { 
        data_parsed = JSON.parse(data);

        if(data_parsed.length > 0)
        {
            //i don't know the structure of your data, but put the right thing here.
            $("#unreadNotification").text(data_parsed.unreadNotification);
        }
    });
}

Call that function every 10 seconds.

setInterval(notifications, 10000);
Mathieu Labrie Parent
  • 2,598
  • 1
  • 9
  • 10