0

How do you post a form(in javascript) and make the browser not wait for response? Is this possible at all? The pattern I want to create is a sort of "Fire and Forget" pattern. Here is the code that performs the submittion:

var iframe = document.createElement("iframe");
var unikString = "UNIQUE STRING";
document.body.appendChild(iframe);
iframe.style.display = "none";
iframe.contentWindow.name = unikString;

var form = document.createElement("form");
form.target = unikString;
form.action = "[THEURL]";
form.method = "POST";

document.body.appendChild((function(){
    document.createElement("input");
    input.type = "hidden";
    input.name = "NAME";
    input.value = "VALUE";
    return input;
})());

setTimeout(function ()
{
    form.submit();
}, 0);

(The form posting is done this way because i have to post to an end point outside the domain, and therefore the CORS problem must be overcome.)

sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
Stian Standahl
  • 2,188
  • 3
  • 28
  • 42

1 Answers1

0

If the server receiving the script can be amended and they use PHP they can instate a ignore user abort which will allow the form posting to execute even if the user closes the iframe or window. The only problem with this is that you don't (and never) know whether this worked correctly as you are ignoring the response.

http://php.net/manual/en/function.ignore-user-abort.php

Otherwise the form you are posting will allows be ignored. The only thing you can do is create a response to the the response of the form. Otherwise you can always just ignore it.

somethinghere
  • 14,155
  • 2
  • 23
  • 39
  • how does client side javascript handle this? does it wait for a response until it times out? – Stian Standahl Oct 15 '14 at 08:10
  • Since you are using an iframe it doesn't really matter. The iframe will print the 'response' in the frame, but you can just continue the execution after inserting the iframe and directing it to the URL. Javascript itself is asynchronous in that it continues execution unless you ask it to wait for something, which you aren't. (i.e. the only action you do is inserting an iframe with a url, javascript does that and moves on. If you use `iframe.load(fn)`, then the `fn` gets triggered on load. _Then_ javascript 'waits'). – somethinghere Oct 15 '14 at 08:14