Reena Verma
Reena Verma

Reputation: 1685

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.

Upvotes: 0

Views: 2578

Answers (1)

swift-lynx
swift-lynx

Reputation: 3765

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

Upvotes: 2

Related Questions