Search code examples
javascriptjqueryajaxpartial-page-refresh

Page with Ajax function does not refresh data


My scripts are working perfectly fine. However, the content does not refresh itself to get new data. Why is it so?

 function updateMsg() {
    $.ajax({
       url: "/recent/notifications/",
       cache: false,
       success: function(html){     
         $("#profile_notifarea_msgbox").html(html);
       }
    });
    setTimeout('updateMsg()', 4000);
 }
 updateMsg();   

Solution

  • Your setTimeout can reference updateMsg directly instead of using a string:

    var timeout;
    
    function updateMsg() {
       $.ajax({
          url: "/recent/notifications/",
          cache: false,
          success: function(html){     
            $("#profile_notifarea_msgbox").html(html);
            timeout = setTimeout(updateMsg, 4000);
          }
       });       
    }
    updateMsg();   
    
    function stopUpdate() {
        clearTimeout(timeout);
    }
    

    To stop the continuous update you save a reference to the setTimeout in a variable and then call clearTimeout and pass in that variable. In this example, you would just call the function stopUpdate() to cancel the updates.