Initially I was using jQuery.ajax call to send a request to server before user
leave the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
window.onbeforeunload = function(evt) {
const endpoint = '/lock/end-timestamp.php';
$.ajax({
url: endpoint,
dataType: 'json',
type: 'post',
async: false, // synchronous request
data: {
_token: $('meta[name="csrf-token"]').attr('content'),
param1: 'data1',
param2: 'data2',
},
});
};

And I set the async to false, it doesn’t work.

After googled, I found a better solution navigator.sendBeacon, and it works well.

1
2
3
4
5
6
7
8
window.onbeforeunload = function(evt) {
const endpoint = '/lock/end-timestamp.php';
var formData = new FormData();
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
formData.append('param1', 'data1');
formData.append('param2', 'data2');
navigator.sendBeacon(endpoint, formData);
};

References: