Reload page after message is shown, jQuery

Ilja picture Ilja · Dec 6, 2011 · Viewed 51.3k times · Source

Right now I have a form where user enters the info. It is than processed bu jQuery ajax function and is set to return false; so no page reload happens after user submits a form. Although I need to reload page, but if I remove return false; it refreshes page before success message is shown (this message is shown after user submits data).

     $.ajax({
      type: "POST",
      url: "scripts/process.php",
      data: dataString,
      success: function() {
       $("#st_message").html("<p> Your article was successfully added!</p>");
       //I need to reload page after the above message is shown
      }
     });
    return false;

So how can I reload page after the <p> Your article was successfully added!</p> message is shown, with a slight delay say 2 - 3 seconds, so user can actually read the message.

Answer

Rion Williams picture Rion Williams · Dec 6, 2011

You could add a delay by using the setTimeout() function, such as:

// This will reload the page after a delay of 3 seconds
window.setTimeout(function(){location.reload()},3000)

For your needs:

$.ajax({
      type: "POST",
      url: "scripts/process.php",
      data: dataString,
      success: function() {
           $("#st_message").html("<p> Your article was successfully added!</p>");
           window.setTimeout(function(){location.reload()},3000)
      }
});
return false;

Working Example