In my project I am migrating to React and so not loading JQuery. Since I don't have JQuery anymore, for AJAX calls I am using fetch. With JQuery I can hook the start and end of AJAX calls so it's very easy to change the cursor to a spinner. I can't find similar hooks in fetch. Is there a way to do this other than changing it in each individual AJAX call?
Lots of Googling just kept finding answers about... JQuery.
Fetch is compatible with all recent browsers including Edge, but not with Internet Explorer. Therefore, if you are looking for maximum compatibility, you will continue to use Ajax to update a web page. If you also want to interact with the server, the WebSocket object is also more appropriate than fetch.
Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP. The fetch specification differs from jQuery.ajax() in the following significant ways: The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500.
Fetch is an interface for making AJAX calls in JavaScript. It is implemented widely by modern browsers and is used to call an API. Calling fetch returns a promise, with a Response object.
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
Fetch in thenable, you can add spinner stop function in then(), that is called after response is received. And wrap it in another function for headers and hooking.
function ajax(someUrl, method) {
var myHeaders = new Headers();
var myInit = {
method: method,
headers: myHeaders
};
showSpinner();
return fetch(someUrl, myInit).then(function(response) {
//... do some with response
hideSpinner();
return response;
}).catch(function(error) {
//... tell the user the request failed and hide the spinner
hideSpinner();
return error;
});
}
ajax('example.com').then(function(response) {
// ...
}).catch(function(error) {
// show error
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With