We are going to reconstruct the code from the previous exercise step-by-step until we have written a complete AJAX POST request.
Feel free to refer to the XHR POST diagram at any point while completing this exercise:
Create a new
XMLHttpRequest object using the
new operator, and save it in a
Next, save the following URL to a
url. Make sure the URL is wrapped in quotes so that it is a string.
The URL will direct the request to the correct server.
Create a new
data, and save this line of code to it:
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.
responseType property of the
xhr object to be
xhr.onreadystatechange event handler equal to an anonymous arrow function. Leave the function empty until the next step.
.onreadystatechange will contain the event handler that will be called when
xhr‘s state changes.
In the code block of the function you created in the previous step, add a conditional statement that checks to see if the
xhr is equal to
In the code block of the conditional statement, return the
response property of
response property will contain the data that we’re getting back from the POST request.
Below the function you created in the previous two steps, call the
.open() method on the
xhr object and pass it
url as arguments.
.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.
On the following line, call the
.send() method on the
xhr object and pass
data as an argument.
.send() will send the request to the server.
Nice work! You’ve written the boilerplate code for an AJAX
POST request using an