Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a post Request with Javascript on unload/beforeunload. Is that possible? [duplicate]

Added: I cannot use jQuery. I am using a Siemens S7 control unit which has a tiny webserver that cannot even handle a 80kB jQuery file, so I can only use native Javascript. from this link Ajax request with JQuery on page unload I get that I need to make the request synchronous instead of asynchronous. Can that be done with native Javascript?

I copied the code from here: JavaScript post request like a form submit

I was wondering if I could call this on closing the window/tab/leaving the site with jquery beforeunload or unload. Should be possible, right?

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}
like image 273
Coffeehouse Avatar asked Jan 20 '14 07:01

Coffeehouse


1 Answers

Here is one way to do it:

<body onunload="Exit()" onbeforeunload="Exit()">
    <script type="text/javascript">
        function Exit()
        {
            Stop();
            document.body.onunload       = "";
            document.body.onbeforeunload = "";
            // Make sure it is not sent twice
        }
        function Stop()
        {
            var request = new XMLHttpRequest();
            request.open("POST","some_path",false);
            request.setRequestHeader("content-type","application/x-www-form-urlencoded");
            request.send("some_arg="+some_arg);
        }
    </script>
</body>

Note that the request probably has to be synchronous (call request.open with async=false).

One additional notable point of attention:

If the client is terminated abruptly (e.g., browser is closed with "End Process" or "Power Down"), then neither the onunload event nor the onbeforeunload will be triggered, and the request will not be sent to the server.

like image 193
barak manos Avatar answered Oct 07 '22 19:10

barak manos