How to reload page with javascript without sending POST information again
Asked Answered
B

3

13

I have a page, to which I POST information via form method="post". I would like to relaod it with JavaScript, but location.reload(true) and location.reload() makes browsers ask if I want to send the POST data again.

I would like to make JavaScript reload the page with GET instead of POST to skip the POST data.

How can I achieve that?

Barm answered 1/9, 2014 at 19:49 Comment(0)
H
32
window.location.href = window.location.href

try

Hilmahilt answered 1/9, 2014 at 19:51 Comment(5)
Just how easy that was. Had that feeling. Thank you a bunch!Barm
When I do this, the page doesn't reload at all because the URL doesn't changeScrummage
It should. Which browser do you use?Hilmahilt
Confirmed, if I enter this into a Chrome's console, nothing happens (2020)Tortoni
In my Firefox 124.0.1 this shows the confirmation dialog to repost.Carricarriage
M
1

To reload a page without post data using javascript the easiest way I've found is to use an extra form to submit - this works regardless of whether the url is # or anything.

<form name="reloadForm">
    <button type="submit">
        Continue
    </button>
</form>
<script>
    document.reloadForm.submit() ;
</script>

That will show a button briefly on screen that the user can click continue on but the script will automatically submit it - this method sorts out a number of problems - the form is empty so it will not submit any post data (the button isn't named so even that won't submit a value). It works even if the url is set to #, and finally it gives a backup in case the user has disabled javascript (or the javascript doesn't work for some reason) they've still got a continue button available to click.

Mandal answered 31/5, 2020 at 8:38 Comment(2)
I've managed to reduce this idea to this javascript: document.body.innerHTML += '<form name="reloadPage"><input type="hidden" name="_" value="_"></form>'; document.reloadPage.submit();Tortoni
Although I later found out, that it can be unreliable for some reason, probably some user control action - but if I add the form to html first and user makes a click action to which I bind, then the form submission seems to always work.Tortoni
C
0

The accepted response is what I knew too, seems like it has become problematic, jave.web said in 2020 that it did nothing in chrome, currently my firefox pops up the repost dialog. So here's a surefire way to do it, although not the most elegant, it's inspired by jquery's nocache:

location.href = location.href + (location.href.includes('?') ? '&' : '?') + '_=' + Date.now();
Carricarriage answered 26/3 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.