Skip to content

Instantly share code, notes, and snippets.

@Ormadont
Created June 11, 2018 16:37
Show Gist options
  • Save Ormadont/acdd05ed27acdcdbad3c40ead5c44cb6 to your computer and use it in GitHub Desktop.
Save Ormadont/acdd05ed27acdcdbad3c40ead5c44cb6 to your computer and use it in GitHub Desktop.
The boilerplate code for an AJAX POST request using an XMLHttpRequest object.
//The boilerplate code for an AJAX POST request using an XMLHttpRequest object.
//The XMLHttpRequest object is used in JavaScript to interact with servers.
const xhr = new XMLHttpRequest();
//The URL will direct the request to the correct server.
const url = 'https://api-to-call.com/endpoint';
//JSON.stringify() will convert a value to a JSON string.
//By converting the value to a string, we can then send the data to a server.
const data = JSON.stringify({id: '200'});
xhr.responseType='json';
//.onreadystatechange will contains the event handler that will be called when xhr's state changes.
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
//The response property will contain the data that we're getting back from the POST request.
return xhr.response;
}
}
//.open() creates a new request and the arguments passed in determine what type of request is being made
//and where it's being made to.
xhr.open('POST', url);
//.send() will send the request to the server.
xhr.send(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment