0

This is similar to, but not the same as How can I refresh a page with jQuery?:

I bring up a modal form that collects some stuff from the user and passes it off to the server via a $.ajax() call. The server sends back a path that should become the new window.location of the browser. So the ajax call wants to be something like:

$.ajax({
   // stuff

   success: function (destination) {
      // other stuff
      window.location = destination;
   }),

   // still more stuff
});

This works fine as long as destination is a pure path, like /some_path and if the browser is not currently on that page. However, if the path is the page that I'm currently on and also includes a target -- /some_path#some_target, I lose: the browser simply repositions the page at the specified target, but does not hit the server for a fresh view of the page, which I need (since the server has done some stuff during the ajax call).

So, maybe I just add a location.reload() after the window.location call? That would work when the code is running on the page to which it's being returned, I think. But if I'm on another page, I get hit by a race condition, where the reload is called before the browser has finished making the window.location change, and I get the old page reloaded, not the new destination.

Blurgh. Is there any way around this?

Community
  • 1
  • 1
Jim Miller
  • 3,291
  • 4
  • 39
  • 57

2 Answers2

2

One approach would be to check if window.location.pathname (which is the path without # or ?) is the same as destination within your success callback:

 success: function (destination) {
      // other stuff
      if (destination === window.location.pathname) {
          window.location.reload(); // reload if we are on the same page
      } else {
          window.location = destination; // otherwise, navigate to "other" page
      }
   }),
Nick Tomlin
  • 28,402
  • 11
  • 61
  • 90
0

window.location.reload() reloads the current page with POST data, while window.location.href=window.location.href does not include the POST data.

Netwidz
  • 179
  • 4