var form = document.forms['userinfo'];
var formData = new FormData(form);
function ajaxstuff(event) {
event.preventDefault();
fetch('/userinfo', {
method: 'POST',
body: formData
})
}
form.addEventListener('submit', ajaxstuff);
You need to create the FormData object inside ajaxstuff(), otherwise it’s created when the page loads and the form is empty, which is why you don’t get any values sent to the server.
function ajaxstuff(event) {
event.preventDefault();
var formData = new FormData(form);
fetch('/userinfo', {
method: 'POST',
body: formData
});
}
FormData can handle binary data (i.e file uploads), as it encodes the data as a multipart form.
Using something like jQuery’s serialize method turns the data into a URL encoded string (e.g. name=Fred&age=30). You can’t send files this way, but if you’re only sending string data then it’s more efficient (less overhead on the request).