Send POST data using XMLHttpRequest
Using an XMLHttpRequest
to POST data? Serialize your payload with JSON.stringify()
. Make sure to set Content-Type to 'application/json'
for proper server handling.
Breaking down the code
Defining your request headers
In POST
requests, letting the server know what kind of data you're sending is essential. We're using the 'application/json'
MIME type here, but it can be changed to 'application/x-www-form-urlencoded'
if you're sending form data instead.
URL encoding and payload preparation
Before our data can embark on its journey, we first need to package it up. This process, known as encoding, is fundamental for most POST
requests.
Listening to state changes
Keep an eye on your request's progress with onreadystatechange
. Check for completion with readyState == 4
, then handle the response based on this.status
.
Convenience of FormData
FormData
is an object that simplifies data serialization, especially when making POST
requests using forms. It can append key-value pairs similar to how you'd fill out a form.
Don't forget error handling
Every epic saga has a hero and a villain. Every XMLHttpRequest has a success and an error handler.
Asynchronicity of XMLHttpRequest
Patience is key. By default, XMLHttpRequest won't wait for a request to finish before moving onto the next line of code.
Advanced application
To better grasp your newfound power of POST
requests with XMLHttpRequest
, let's dive deeper into practical usages.
Working it with JSON
When dealing with an API that expects JSON, stringifying your payload is an essential step.
More than just sending data
As with all great powers, XMLHttpRequest comes with some extra goodies.
A word on security
A "secure connection" is a lot more than just a green padlock on your address bar. Always consider security in your requests — avoid exposing sensitive data and consider using security tokens or OAuth.
Was this article helpful?