Documentation indicates sendBeacon
sends its data via a HTTP POST request
,
but in PHP the $_POST
variable seems to be an empty array.
Here is my javascript code : navigator.sendBeacon('beacon_log.php','My lost data')
What am I doing wrong?
Update :
Found that if I use
navigator.sendBeacon('beacon_log.php?g_data=My data ok','Still lost!')
I can access the gdata with $_GET
Why would that be when the $_SERVER['REQUEST_METHOD']=POST
?
Documentation indicates sendBeacon
sends its data via a HTTP POST request
,
but in PHP the $_POST
variable seems to be an empty array.
Here is my javascript code : navigator.sendBeacon('beacon_log.php','My lost data')
What am I doing wrong?
Update :
Found that if I use
navigator.sendBeacon('beacon_log.php?g_data=My data ok','Still lost!')
I can access the gdata with $_GET
Why would that be when the $_SERVER['REQUEST_METHOD']=POST
?
3 Answers
Reset to default 9here is how I get to do it:
Front-end: in my .js file:
window.onbeforeunload = () => {
navigator.sendBeacon('php/record-stats.php', JSON.stringify(stats));
}
Back-end: in my PHP file
$request = file_get_contents('php://input');
$data = json_decode($request);
It was a lot of trial/errors to find it, I couldn't find any doc at the time...
In order to get print_r($_POST,1);
in PHP the data has to be formatted for an HTTP POST request:
window.onpagehide = function(event)
{
var fd = new FormData();
fd.append('ajax', 'beacon');
fd.append('name', 'John');
navigator.sendBeacon(path+'/beacon/', fd);
}
This will yield the desired results for print_r($_POST,1);
in PHP.
Additionally...
- Don't use Beacon with onbeforeunload.
- Don't use Beacon with onvisibilitychange because of WebKit/Safari.
The data from navigator.sendBeacon
is found in $HTTP_RAW_POST_DATA