Created
June 11, 2018 16:37
-
-
Save Ormadont/acdd05ed27acdcdbad3c40ead5c44cb6 to your computer and use it in GitHub Desktop.
The boilerplate code for an AJAX POST request using an XMLHttpRequest object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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