'form data is showing empty after append
$('#submit2').click(e => {
e.preventDefault();
var form_data = new FormData();
form_data.append('newKey1', 'newValue1');
form_data.append('newKey2', 'newValue2');
console.log("data after appended", form_data.get('newKey1'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="submit2">See form data in Console</button>
I want to add files in form data, but I am unable to append, so I tried to add key and values, and I am unable to append this in form data.
Solution 1:[1]
Your FormData
is fine, you just can't console.log
it and expect to see the content.
This is how you would normally use your FormData
:
document.addEventListener('submit', function (event) {
event.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: new FormData(event.target),
}).then(function (response) {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn(error);
});
});
If you want to log the object, you need to do something like this:
var serializeForm = function (form) {
var obj = {};
var formData = new FormData(form);
for (var key of formData.keys()) {
obj[key] = formData.get(key);
}
return obj;
};
serializeForm(formData)
Sources:
Solution 2:[2]
It's not empty you just can't access it like that try this: console.log([...dataForm.entries()])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dimitri Kopriwa |
Solution 2 | sh cs |