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.