I am trying to attach sendBeacon
method to one of the page in my web application. I tried to send request
using a simple AJAX
method and via sendBeacon()
method. Both are giving different results and none is usable. Please suggest.
html.php
<body>
<button onclick="setzero();">
click me
</button>
<script>
function setzero(){
var settings = {
"url":"ttstt.php",
"method":"POST",
"data": JSON.stringify({"val":0})
};
$.ajax(settings).done(function(e){console.log(e);});
}
window.addEventListener("unload", function() {
navigator.sendBeacon("ttstt.php", JSON.stringify({"val":1}));
});
</script>
</body>
ttstt.php
$val = ($_POST);
print_r($val);
When I click the button on html.php
I get the following result.
!! Please note that the complete array is in the key portion. !!
Array
(
[{"val":0}] =>
)
When I reload the page to initiate the sendBeacon()
, I get []
as a result.
I just changed the following in my PHP code
Also same code works with sendBeacon() data also.