Post Data with the JavaScript XMLHttpRequest Method
Hint
-
Create a new XMLHttpRequest.
-
Call the
.open()
method on the instance. Pass it the HTTP request method to use, the URL, and the boolean valuetrue
for the async parameter. -
Call the
.setRequestHeader()
method on the instance. Pass it'Content-Type'
for the header name and'application/json; charset=UTF-8'
for the value. -
Assign a callback function to the
onreadystatechange
property on the instance. Inside the callback, use an if statement to check thereadyState
andstatus
properties for the appropriate values (4
and200
respectively). Inside the if statement callJSON.parse()
with the value from theresponse
property and assign it to a variable. -
Get the DOM element with the class name
message
and assign to itstextContent
property the values from theuserName
andsuffix
properties that are on the variable you saved from callingJSON.parse()
. -
Call
JSON.stringify()
and pass it the object{ userName: userName, suffix: ' loves cats!' }
save the return to a variable namedbody
. -
Call
.send()
on the instance. Pass it thebody
variable.
Solutions
Solution 1 (Click to Show/Hide)
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('sendMessage').onclick = function(){
const userName = document.getElementById('name').value;
const url = 'https://jsonplaceholder.typicode.com/posts';
// Add your code below this line
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201){
const serverResponse = JSON.parse(xhr.response);
document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix;
}
};
const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
xhr.send(body);
// Add your code above this line
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Friends</h1>
<p class="message">
Reply from Server will be here
</p>
<p>
<label for="name">Your name:
<input type="text" id="name"/>
</label>
<button id="sendMessage">
Send Message
</button>
</p>
Relevant Links
- MDN: XMLHttpRequest
- MDN: Using XMLHttpRequest
- MDN: HTTP request methods