I can't seem to get the data from the Beacon API post request so that I can save it in my logs table. If there's no support for the Beacon API then I fallback to an AJAX request. The url is correct. I'm able to send an AJAX request, but navigator.sendBeacon doesn't seem to be working for me. Here's my js code:
// Wait for the DOM to be ready
$(function() {
function sendAnalytics() {
if (navigator.sendBeacon) {
let logVisit = function() {
// Test that we have support
if (!navigator.sendBeacon) return true;
// URL to send the data to, e.g.
let url = $('#conference-wrapper').data('url');
// Data to send
let data = new FormData();
data.append('status', 'left');
// Let's go!
navigator.sendBeacon(url, data);
};
window.addEventListener('beforeunload', logVisit);
} else {
var data = {},
url = $('#conference-wrapper').data('url');
if(typeof url !== 'undefined' && url !== ''){
data.status = 'left';
$.ajax({
method: "POST",
url: url,
dataType: "json",
data: data
}).done(function(response) {
console.log('done');
console.log(response);
}).fail(function(response) {
console.log('fail');
console.log(response);
});
}
}
}
window.addEventListener('beforeunload', function() {
sendAnalytics();
});
});
My route in web.php:
Route::post('{id}/participant-left', 'MyController@onParticipantLeft')->name('my.controller.participant.left');
My Controller:
public function onParticipantLeft(Request $request)
{
Log::create([
'status' => $request->status,
]);
}
What am I doing wrong?