Categories
JavaScript Answers

How to Run Code After jQuery Ajax Calls Regardless of the Result?

Spread the love

Sometimes, we want to run code after jQuery Ajax calls regardless of the result.

In this article, we’ll look at how to run code after jQuery Ajax calls regardless of the result.

Run Code After jQuery Ajax Calls Regardless of the Result

To run code after jQuery Ajax calls regardless of the result, we can call the always method.

For instance, we can write:

$.ajax({  
  url: 'https://yesno.wtf/api',  
  dataType: 'json',  
  type: 'GET'  
}).then((processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) => {  
  console.log('success')  
}).always(() => {  
  console.log("always run");  
});

We call ajax with an object that has the url of the request.

dataType is set to 'json' to make a JSON request.

type is set to 'GET' to make a GET request.

Then we call then with a callback to get the response of the request when it’s successful.

And then we call always with a callback that runs regardless of the request result.

Conclusion

To run code after jQuery Ajax calls regardless of the result, we can call the always method.

Leave a Reply

Your email address will not be published. Required fields are marked *