Created
November 3, 2019 01:08
-
-
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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