[jquery] jQuery Refresh/Reload Page if Ajax Success after time

I use Jquery to make an Ajax request. The server returns Json object with value "true or false" like this:

return Json(new { success = false, JsonRequestBehavior.AllowGet });

Is there any way to refresh page after 5 seconds if the server returns true?

This question is related to jquery ajax

The answer is


var val = $.parseJSON(data);
if(val.success == true)
{
 setTimeout(function(){ location.reload(); }, 5000);

}

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

I prefer this way Using ajaxStop + setInterval,, this will refresh the page after any XHR[ajax] request in the same page

    $(document).ajaxStop(function() {
        setInterval(function() {
            location.reload();
        }, 3000);
    });

location.reload();

You can use the reload function in your if condition for success and the page will reload after the condition is successful.


In your ajax success callback do this:

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

As you want to reload the page after 5 seconds, then you need to have a timeout as suggested in the answer.


if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}

Lots of good answers here, just out of curiosity after looking into this today, is it not best to use setInterval rather than the setTimeout?

setInterval(function() {
location.reload();
}, 30000);

let me know you thoughts.