Skip to content

Instantly share code, notes, and snippets.

@iansinnott
Created November 2, 2016 07:06
Show Gist options
  • Select an option

  • Save iansinnott/d6f913fd825f732e5908d6a1d6fa038a to your computer and use it in GitHub Desktop.

Select an option

Save iansinnott/d6f913fd825f732e5908d6a1d6fa038a to your computer and use it in GitHub Desktop.
Quick XHR API intro
const ajax = (method, url, success) => {
// Create the new XHR
const xhr = new XMLHttpRequest();
// "Open" the request. I.e. configure its method and request URL
xhr.open(method, url);
// Set up a success handler. For XHR we need to respond to changes in the readyState. However,
// the readyState can change for a number of reasons and we are only interested in the change
// that represents completion of the request. So we check whether readyState is equal to
// xhr.DONE, and if it is then we also check that the status was a success (200)
xhr.onreadystatechange = () => {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
success(xhr.responseText);
}
};
// Actually send the request
xhr.send();
return xhr;
};
// Example:
// ajax(
// 'GET',
// 'https://api.github.com/users/iansinnott',
// (responseText) => console.log(responseText)
// );
@iansinnott
Copy link
Copy Markdown
Author

NOTE: There is no error handling built into this function. It basically won't do anything if the server responds with a non-200 status code. This is a significant limitation, but this example is just to remind myself in a simple case how the xhr API works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment