I’m using the code below to do a POST request to an API and grab some data from the server
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/json; charset=UTF8");
request.setRequestHeader("X-Accept", "application/json");
request.send(JSON.stringify(data));
My issue is how to decide if I should do it asynchronous or synchronous. Well actually my issue with async is that I’m not sure how to apply an eventListener which would listen to the completion of that XHR.
If I use asynchronous calls my web application fetches the data too late and the application loads with the previously cache data, though If I use synchronous calls it takes about a second to fetch and display the data and I’m not sure how to display a “loading” icon since I’m not sure where to attach the eventListener.
Could someone make it clear on how to use XHR properly?
I’d like to mention that this is my first time trying to use XHR to fetch data from a server through an API.
Stick with asynchronous, as it doesn’t freeze the browser and allows for a more elegant way of dealing with the response. As for the completion of the XHR, use this:
As always, it’s a good idea to read some documentation on it: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest
“my web application fetches the data too late and the application loads with the previously cache data” – I’m not sure exactly what you mean by that, but if you explain more how your code above is being called/used, I’m sure it could be reorganized to work together properly.