I am making a form that downloads the data the user puts into it. So far the file downloads, but instead of the user's input it returns
[object Object]
I tried using JSON.Stringify(). But it is returning a file with "undefined" inside it. Even though the console.log() is giving me {username: "asdasd", password: "sdasdasd"}
.
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
var formDataString = JSON.stringify(FormData);
// ... submit to API or something
download(formDataString, 'json.txt', 'text/plain');
};
const initialFormData = Object.freeze({
username: "",
password: "",
});
function download(formDataString, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([formDataString], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
My full code is viewable here.
If you check lines 2 and 3 of snippet reported here, the answer is pretty simple: you're saying JSON.stringify(FormData)
with capital F , while the console.log
outputs formData
with lower f
Variables are case-sensitive in JavaScript, so FormData
is never defined (undefined
), while formData
is what you have correctly defined above, and console.log(formData)
correctly outputs in the console the content of the variable.