21

I need to reload a page in a success of an ajax call.

I'm seeing some code (not mine) and there are two ways:

success: function(obj) {
  //code
  location.href = location.href;
}

or

success: function(obj) {
  //code
  window.location.reload(true);
}

Is there any difference in the behaviour? I know the difference of both location and window.location but in terms of do the job?

pmiranda
  • 7,602
  • 14
  • 72
  • 155
  • 3
    Possible duplicate of [Difference between window.location.href=window.location.href and window.location.reload()](http://stackoverflow.com/questions/2405117/difference-between-window-location-href-window-location-href-and-window-location) – Farkhat Mikhalko Dec 07 '16 at 14:48
  • 2
    the `window.location.reload(true);` reloads the page from the server instead of from the cache, `window.location.reload();` would do the same thing as `location.href = location.href;` except for that the `window.location.reload()` includes a post. – Kevin Kloet Dec 07 '16 at 14:49

2 Answers2

24

The main difference is follow:

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

Further more, window.location.reload(true) method reload page from the server. And the browser will skip the cache.

For example, I see you are using success function from an AJAX request.

Suppose you have follow method:

[OutputCache(Duration=600)]
public ActionResult Homepage(){
   //code here
   return View();
}

If you are using window.location.href="location_URL",then browser cache data for 600 seconds, which means 10 minutes.

On the other hand, if you use window.location.reload(true), then the browser will skip the cache and ,then, reload page from server.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • 4
    also, `window.location.href=window.location.href` will not reload the page if there's an anchor (#) in the URL – adl Apr 01 '19 at 09:51
  • 1
    Important note: The `forceGet` parameter for `location.reload()` is [only available in Firefox](https://developer.mozilla.org/en-US/docs/Web/API/Location/reload#location.reload_has_no_parameter)! – Venryx Feb 02 '22 at 14:05
1

My version, using above, as a Razor button handler:

private async Task  Reset()
{
    await js.InvokeVoidAsync("window.location.reload",true);
}
David Jones
  • 542
  • 4
  • 13