Hey everyone, I’m trying to figure out how to send form data using the Fetch API. I’ve been playing around with it, but I’m not getting the results I want. Here’s what I’ve tried:
let formSubmit = async () => {
let formElement = document.getElementById('userForm');
let response = await fetch('/api/submit', {
method: 'POST',
body: new FormData(formElement),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
let result = await response.json();
console.log(result);
};
The problem is, it’s sending the data as multipart/form-data instead of application/x-www-form-urlencoded like I want. Is there a way to make it use the right content type? Or if not, how can I handle multipart/form-data on the server side?
I know I could manually create the URLSearchParams, but I’m looking for something more like jQuery’s .serialize() method. Any ideas? Thanks!
I’ve encountered this issue before, and there’s a simple solution. Instead of using FormData, you can create a URLSearchParams object from your form. Here’s how you can modify your code:
let formSubmit = async () => {
let formElement = document.getElementById('userForm');
let formData = new URLSearchParams(new FormData(formElement));
let response = await fetch('/api/submit', {
method: 'POST',
body: formData,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
let result = await response.json();
console.log(result);
};
This approach will serialize your form data correctly and send it as application/x-www-form-urlencoded. It’s a good alternative to jQuery’s .serialize() method when working with the Fetch API. Hope this helps!
I’ve been down this road before, and I found that using the URLSearchParams object is the way to go. It’s simple and effective. Here’s what worked for me:
let formSubmit = async () => {
let form = document.getElementById(‘userForm’);
let formData = new URLSearchParams(new FormData(form));
This approach ensures your data is sent as ‘application/x-www-form-urlencoded’. It’s also good practice to add some error handling, as I’ve done here. This has always worked reliably for me across different projects.