There are 4 steps to setting up an XHRHttpRequest:
- Create the object
var xhr = new XHRHttpRequest();
- Open the request
note: This does not send the request yet, but this is where you would set up the headers.
- Wire up the event handlers
- Fire off the request
Step 3 is where the magic happens. The
loadEventHandler function will deal with any and all data coming in from the server and it’s the XHR event we become familiar with first. However, it’s not the only event, and there are a few others to help you out with what you want to do.
xhr.addEventListener('loadstart', beginProgressHandler); //Starts when the connection is successful and the server begins sending a response
xhr.addEventListener('loadend', finishProgressHandler); //Starts when the connection is successful and the server has finished sending a response
xhr.addEventListener('error', cockedUpProgressHandler); //Fires off when the server request is mucked up for whatever reason
I would use the
loadStart handler to make the first change to your button. The
loadend handler would be best for the third state.
timeout should be used to handle their respective problems should they arise. Check out the documentation for a full list of the events available (there aren’t a lot). Doing this instead of relying on timers will ensure that your application is in the state it should be in when you run your code, rather than guessing and hoping.
Hope this helps!