Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX replacement with sendBeacon

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?

like image 205
Israel Correa Quevedo Avatar asked Feb 06 '20 22:02

Israel Correa Quevedo


People also ask

Why use sendBeacon?

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.

What is send beacon?

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 .

Can I make an Ajax call from JavaScript?

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.


1 Answers

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

like image 134
RyDog Avatar answered Sep 30 '22 06:09

RyDog