Search code examples
javascripthttppostxmlhttprequest

Check if POST was successful and then run JavaScript


How do I check, if a POST XHR request was successful, on a website, for a particular URL?

If the POST was successful, I then want to run some JavaScript.

I've seen ways to do this in jQuery, but I want to do this via vanilla JavaScript.


Solution

  • You can use the status code to check if the request was successful:

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
            // successful
        }
    }
    xhr.open('GET', 'http://example.com', true);
    xhr.send();
    

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status

    https://stackoverflow.com/a/3038972/10551293