7

window.location.replace() can issue a GET request to target URL and replace the browser "back" history.

Is there any method to issue a POST request to target URL and replace the browser "back" history as well (with/ without jQuery is fine)?

Currently using the following code to issue a POST request, but it does not replace the "back" history:

var actionForm = $('<form>', {'action': 'register.php', 'method': 'post'}).append($('<input>', {'name': 'action', 'value': 'user_register', 'type': 'hidden'}));
actionForm.appendTo('body').submit();
Raptor
  • 53,206
  • 45
  • 230
  • 366

1 Answers1

3

you might want to do something like these.

 $.ajax({
     url: "your url here",
     type: "POST",
     data: {
         field1: "value1",
         field2: "value2",
         field3: "value3"
     },
     success: function (response) {
         if (response.successFlag) {
             //Replace current location from the history via history API
             window.history.replaceState({}, 'foo', '/foo');
             window.location = "url of target location here if you want to send a get request";
             $("#form-id").submit();//if you want to post something up
         }
     }
 });

I'm thinking maybe you would also get rid of the need for removing the history using this approach.

OR

you can use the following to replace the record of the current page from the history and submit your form.

window.history.replaceState({}, 'foo', '/foo');
$("#form-id").submit();

OR

you can use the following code when the next page loads and you want to remove the record of the next page from the history:

    window.history.replaceState({}, 'foo', '/foo');
Allan Chua
  • 9,305
  • 9
  • 41
  • 61
  • Thanks for the reply. But if my script, let's say `test.php`, checks for POST parameter only (and will redirect away if the POST parameter is not present), will the line `window.location` causes problem (as in theory assigning `window.location` is a GET reqeust)? – Raptor Aug 10 '15 at 03:30
  • 1
    the last option is most useful, as the first two will submit the information twice. thanks for your help. – Raptor Aug 10 '15 at 04:05
  • 1
    **Version note:** only supports since IE10 ([ref](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history)) – Raptor Aug 10 '15 at 04:06