Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created November 3, 2019 01:08
Show Gist options
  • Save luisenriquecorona/da301430ddb83a1cd33159f731d65055 to your computer and use it in GitHub Desktop.
Save luisenriquecorona/da301430ddb83a1cd33159f731d65055 to your computer and use it in GitHub Desktop.
As you can see in this example, we do nothing if the post fails. This is usually fine when XHR is used to capture broad user statistics, but if it’s crucial that the data makes it to the server, you can add code to retry on failure:
function xhrPost(url, params, callback) {
var req = new XMLHttpRequest();
req.onerror = function() {
setTimeout(function() {
xhrPost(url, params, callback);
}, 1000);
};
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (callback && typeof callback === 'function') {
callback();
}
}
};
req.open('POST', url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setRequestHeader('Content-Length', params.length);
req.send(params.join('&'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment