21

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?

Anh Hoang
  • 2,242
  • 3
  • 22
  • 23

8 Answers8

57

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.

Jai
  • 74,255
  • 12
  • 74
  • 103
17
location.reload();

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

Buttle Butkus
  • 9,206
  • 13
  • 79
  • 120
Vikas Gautam
  • 997
  • 7
  • 23
10
if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
4

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);
    });
A. El-zahaby
  • 1,130
  • 11
  • 32
2
var val = $.parseJSON(data);
if(val.success == true)
{
 setTimeout(function(){ location.reload(); }, 5000);

}
AVM
  • 592
  • 2
  • 11
  • 25
1
$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
1

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.

  • setTimeout function is called one time only, the setInterval will be called many times. You know which one is suitable and better in this case – Anh Hoang Aug 05 '19 at 09:24
1

Just use

    $.ajax({
        success: function (response) {
            location.reload();
            },
        error : function(xhr,errmsg,err) {
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
    }
    });