Ever wanted to send form data via AJAX? A great and easy way to do this is via FormData.
Requirements:
HTML: Any form will do. JavaScript: XHR2 http://caniuse.com/#feat=xhr2 FormData is part of the Javasctipt Web API and can be used to send data in the form of Key/value pairs.
As said earlier a basic form will do for this, just like the basic form we have below:
<form class="js-form-to-send" action="/to/endpoint" method="post">
<input type="text" name="myText" value="">
</form>
Lets start our JavaScript by creating our instance of FormData.
const myForm = document.getElementById('myForm');
const formData = new FormData(myForm);
Now that we have our Form we can set up sending our data via XHR.
const xhr = new XMLHttpRequest();
xhr.open('POST', '/to/endpoint', true);
xhr.onload = function() {
if(xhr.status === 200) {
console.log('Yay it works');
} else if (xhr.status === 400) {
console.log('Bad Request :(');
}
};
xhr.send(formData);
We are using the newer xhr2 or (XMLHttpRequest Level 2) allows us to send data via a HTTP request and is a great improvement XMLHttpRequest Level 1. What we do is create a new instance of xhr, set up the target URL and method with:
xhr.open('method', 'url', 'async');
We then add the code for handling our response from the endpoint with:
xhr.onload = function() {
};
XHR provides us with a number of useful data that we can use in our application such as: xhr.status - status code from the web server xhr.response - the response, this can be anything from text to a JSON response.
Then finally we send our form data with:
xhr.send(formData);
That's it our data would be sent to the end point. If you need to append data you can do it like this:
formData.append('key', 'value);
It is important to note that you shouldn't send a Content-Type header as this will cause the request to fail. That's it on this post, I hope you found it useful.