I'm sorry in advance, my native language is not English :(
Since in Chrome version 80 the AJAX queries no longer work in the unload event, I require another alternative, I read about Navigator.sendBeacon the problem is that I did not find an example to send multiple data, for example in AJAX have this:
$(window).on('unload', function() {
console.log('ajax unload');
$.ajax({
type: 'POST',
url: 'config/myphpfile.php',
async: false,
data: {
xvar1: var1,
xvar2: var2,
xvar3: 0
},
success: function(data) {
console.log('work!');
}
});
As you can see in this AJAX event, it sent 3 variables to my PHP, and one of them the var2 is an array, how can I pass multiple variables in the same way with the Navigator.sendBeacon function, have you done something similar?
sendBeacon is particularly useful if you want to send a small amount of data and do not particularly care about a response. navigator. sendBeacon(url, data); One of — if not the — main use for sendBeacon is to solve the issue of asynchronous requests being cancelled by the browser.
sendBeacon() method asynchronously sends an HTTP POST request containing a small amount of data to a web server. It's intended to be used for sending analytics data to a web server, and avoids some of the problems with legacy techniques for sending analytics, such as the use of XMLHttpRequest .
Ajax is a programming concept. Below are some ways to make Ajax call in JavaScript. Approach 1: In this approach, we will use the XMLHttpRequest object to make Ajax call. The XMLHttpRequest() method which create XMLHttpRequest object which is used to make request with server.
You could use the FormData Object
// URL to send the data to
let url = '/api/my-endpoint';
// Create a new FormData and add a key/value pair
let data = new FormData();
// Append data to FormData object
data.append('xvar1', var1);
data.append('xvar2', var2);
data.append('xvar3', 0);
let result = navigator.sendBeacon(url, data);
if (result) {
console.log('Success!');
} else {
console.log('Failure.');
}
I based this solution from: https://www.smashingmagazine.com/2018/07/logging-activity-web-beacon-api/#using-navigator-sendbeacon
Read more about the FormData Object here: https://developer.mozilla.org/en-US/docs/Web/API/FormData
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With