64

When a user visits my website there is a "Login" link on every page. Clicking this uses some JavaScript to show an overlay window where the user is prompted for their credentials. After entering these credentials an Ajax call is made to the web server to validate them; if they are valid, an authentication ticket cookie is sent back and the page is reloaded so that any content on the page that is specific to authenticated users or the (now) currently logged in user is displayed.

I am accomplishing the page reload via script using:

window.location.reload();

This works wonderfully for pages loaded via a GET request (the vast majority), but some pages use postback forms. So if a user goes to one of these pages, performs a postback, and then chooses to login, when the window.location.reload() script runs they are prompted with the dialog box asking if they want to resubmit the POST body.

Resubmit POST body dialog box

I thought to get around this I could just tell the browser to reload the page, so I tried:

window.location.href = window.location.href;

But the browser doesn't take any action with the above statement, I presume because it's thinking the new URL is the same as the old. If I change the above to:

window.location.href = window.location.pathname;

It reloads the page, but I lose any querystring parameters.

My current workaround is sufficient, but not pretty - in short, I tack on a querystring parameter to the current window.location.href value and then assign that back to window.location.href by calling reloadPage("justLoggedIn"), where the reloadPage function is:

function reloadPage(querystringTackon) {
    var currentUrl = window.location.href;

    if (querystringTackon != null && querystringTackon.length > 0 && currentUrl.indexOf(querystringTackon) < 0) {
        if (currentUrl.indexOf("?") < 0)
            currentUrl += "?" + querystringTackon;
        else
            currentUrl += "&" + querystringTackon;
    }

    window.location.href = currentUrl;
}

This works, but it results in the URL being www.example.com/SomeFolder/SomePage.aspx?justLoggedIn, which seems tacky.

Is there a way in JavaScript to get it to do a GET reload and not prompt the user to resubmit the POST data? I need to make sure that any existing querystring parameters are not lost.

Scott Mitchell
  • 8,659
  • 3
  • 55
  • 71
  • how about: `window.location.href = window.location.href + '&reload=1';` ? – drudge Feb 02 '11 at 01:13
  • 1
    @jnpcl: That, in essence, is my current workaround (see the `reloadPage` function I note above), but it feels tacky. I'm hoping there's a more elegant solution. – Scott Mitchell Feb 02 '11 at 03:04
  • Strange that `window.location.href = window.location.href` worked for me (reload the page) under Firefox and Chromium. Maybe try `window.location.replace(window.location.href)` (that additionally makes the page reload transparent to the user history) ... – Pierre Feb 02 '11 at 03:54

14 Answers14

53
window.location.href = window.location.href;

Don't ask my why it works..but it does :).
Just the way the js engine interprets the logic I suppose.

MBT
  • 21,733
  • 19
  • 84
  • 102
peaceslp
  • 699
  • 5
  • 2
  • Does not work for GET either, at least on Firefox this does nothing. – Max Jan 22 '14 at 09:38
  • 21
    Funny how this apparently doesn't do what it's supposed to do, yet people visiting this page keep up voting it... Maybe people come to this page attempting to do the *opposite* of what the OP intended? (e.g. "reload" the page and omit POST parameters) – rinogo Oct 17 '14 at 14:00
  • 1
    Thanks for this answer. It does work across browsers. However I have to state that it only works on all browsers if after form is submitted it doesn't load the same page. @rinogo – w3shivers Nov 26 '14 at 08:00
  • 1
    This is not a good answer since, the post data is just not sent. – Jawad El Fou Dec 23 '20 at 16:52
9

What you probably need to do is redirect the user after the POST / Form Handler script has been ran.

In PHP this is done like so...

<?php
// ... Handle $_POST data, maybe insert it into a database.
// Ok, $_POST data has been handled, redirect the user
header('Location:success.php');
die();
?>

... this should allow you to refresh the page without getting that "Send Data Again" warning.

You can even redirect to the same page (if that's what you're posting to) as the POST variables will not be sent in the headers (and thus not be there to re-POST on refresh)

Daniel Doezema
  • 1,592
  • 10
  • 13
  • 1
    The problem is the application is an ASP.NET Web Forms app, so there are a lot of postbacks and I can't modify this ingrained ASP.NET functionality. – Scott Mitchell Feb 03 '11 at 20:32
  • 1
    That modification to the .NET functionality might warrant another question. I guess what I'm trying to say is that the "solution" to this problem would be attack the cause (Which is not redirecting the user after post) -- I wish I knew more about .NET to help you out there =/ – Daniel Doezema Feb 04 '11 at 16:14
7

This works too:

window.location.href = window.location.pathname + window.location.search
sth
  • 222,467
  • 53
  • 283
  • 367
6

This worked for me.

window.location = window.location.pathname;

Tested on

  • Chrome 44.0.2403
  • IE edge
  • Firefox 39.0
A Web-Developer
  • 868
  • 8
  • 29
5

Use

RefreshForm.submit(); 

instead of

document.location.reload(true); 
Matt Busche
  • 14,216
  • 5
  • 36
  • 61
  • 1
    If you're using jQuery, you can add a unique id to your submit button and then call `$("my_button_id").click()` – krick Jan 21 '16 at 23:11
  • this is the best solution. You can control exactly what data is sent this way. – John Lord Feb 08 '22 at 17:19
3

This can be solved also with POST/REDIRECT/GET pattern.
Which is more elegant:
How do I reload a page without a POSTDATA warning in Javascript?

Community
  • 1
  • 1
trante
  • 33,518
  • 47
  • 192
  • 272
3

I had the same problem as you.

Here's what I did (dynamically generated GET form with action set to location.href, hidden input with fresh value), and it seems to work in all browsers:

var elForm=document.createElement("form");
elForm.setAttribute("method", "get");
elForm.setAttribute("action", window.location.href);

var elInputHidden=document.createElement("input");
elInputHidden.setAttribute("type", "hidden");
elInputHidden.setAttribute("name", "r");
elInputHidden.setAttribute("value", new Date().getTime());
elForm.appendChild(elInputHidden);

if(window.location.href.indexOf("?")>=0)
{
    var _arrNameValue;
    var strRequestVars=window.location.href.substr(window.location.href.indexOf("?")+1);
    var _arrRequestVariablePairs=strRequestVars.split("&");
    for(var i=0; i<_arrRequestVariablePairs.length; i++)
    {
        _arrNameValue=_arrRequestVariablePairs[i].split("=");

        elInputHidden=document.createElement("input");
        elInputHidden.setAttribute("type", "hidden");
        elInputHidden.setAttribute("name", decodeURIComponent(_arrNameValue.shift()));
        elInputHidden.setAttribute("value", decodeURIComponent(_arrNameValue.join("=")));
        elForm.appendChild(elInputHidden);
    }
}

document.body.appendChild(elForm);
elForm.submit();
oxygen
  • 5,891
  • 6
  • 37
  • 69
  • Any idea how to do something like this but still allow for hashes on the URL to be preserved? – jamauss Jul 14 '13 at 05:22
  • @jamauss Have you tried setting the hash on the action URL using the code above? – oxygen Jul 14 '13 at 09:44
  • @jamauss The real question is: why didn't you? – oxygen Jul 14 '13 at 11:06
  • I didn't think hashes were allowed on form action URLs. I tried it now and the problem I have is that it ends up URL encoded. So instead of submitting a form to mysite/thread?thread=3#17 is submits to mysite/thread?thread=3%2317 and so the thread querystring value ends up being 3%2317 instead of 3. – jamauss Jul 14 '13 at 11:13
  • Maybe you can work around it by setting a query parameter "_fragment", and then do a second reload by setting location.href. – oxygen Jul 14 '13 at 11:25
  • So I was able to get it so that the form action URL was like mysite/thread?#17 with a hidden input named "thread" with a value of "3" and the page would not refresh when the form.submit() was called. Not sure why. – jamauss Jul 14 '13 at 11:26
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/33437/discussion-between-jamauss-and-tiberiu-ionu-stan) – jamauss Jul 14 '13 at 11:34
2

This is an older post, but I do have a better solution. Create a form containing all of your post values as hidden fields and give the form a name such as:

<form name="RefreshForm" method="post" action="http://yoursite/yourscript">
    <input type="hidden" name="postVariable" value="PostData">
</form>

Then all you need to do in your setTimeout is RefreshForm.submit();

Cheers!

stealthyninja
  • 10,343
  • 11
  • 51
  • 59
Stephen
  • 21
  • 1
  • 1
    This will attempt to resend all the post information. Why would you copy post data and resend? What you actually want to do is to reload the page without a post – Ruan Mendes Apr 21 '11 at 00:23
1

If you have hashes '#' in your URL, all the solutions here do not work. This is the only solution that worked for me.

var hrefa = window.location.href.split("#")[1];
var hrefb = window.location.href.split("#")[2];
window.location.href  = window.location.pathname +  window.location.search + '&x=x#' + hrefa + '#' + hrefb;

The URL has to be different for it to reload if you have a hash. The &x=x does that here. Just substitute this for something you can ignore. THis is abit of a hack, unable to find a better solution..

Tested in Firefox.

PodTech.io
  • 4,874
  • 41
  • 24
1

You could try to create an empty form, method=get, and submitting it.

<form id='reloader' method='get' action="enter url here"> </form>
<script>
// to reload the page, try
document.getElementById('reloader').submit();
</script>
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1

When we want to refresh the parent page from the child page without any prompt.

Here is the code:

window.opener.location.href = window.opener.location;

This simply refreshes the parent page without any prompt.

Sheo Dayal Singh
  • 1,591
  • 19
  • 11
0

To reload opener window with all parameters (not all be sent with window.location.href method and method with form.submit() is maybe one step to late) i prefer to use window.history method.

window.opener.history.go(0);
Kaster
  • 87
  • 1
  • 6
  • Note: If the page was opened in a new window, this will reload the previous window, not the one you're on. At least in Chrome. – Tony Dec 11 '14 at 22:37
0

You can take advantage of the HTML prompt to unload mechanism, by specifying no unload handler:

window.onbeforeunload = null;
window.location.replace(URL);

See the notes section of the WindowEventHandlers.onbeforeunload for more information.

dsummersl
  • 6,588
  • 50
  • 65
0

This worked

<button onclick="window.location.href=window.location.href; return false;">Continue</button>

The reason it doesn't work without the return false; is that the button click would trigger a form submit. With an explicit return false on it, it doesn't do the form submit and just does the reload of the same page that was a result of a previous POST to that page.

Prasanna
  • 61
  • 1
  • 7