Search code examples
javascriptajaxonbeforeunload

navigator.sendBeacon with application/x-www-form-urlencoded


I'm trying to send a POST request on the beforeunload event using navigator.sendBeacon, but the data doesn't get to the PHP $_POST. I think this is because when using navigator.sendBeacon the header Content-Type is always set to text/plain;charset=UTF-8, but in my case since I need to send a query string and therefore use application/x-www-form-urlencoded.

var amountOfApples = 0;

...

addEventListener("beforeunload", function(e) {
    navigator.sendBeacon("save.php", "key=apples&value=" + amountOfApples);
});

How can I do this and make sure the header is set to application/x-www-form-urlencoded?


Solution

  • Read php://input and run it through parse_str(). Basically:

    $MY_POST = null;
    parse_str(file_get_contents('php://input'), $MY_POST);