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.