Reputation: 11
$('#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.
Upvotes: 1
Views: 3193
Reputation: 81
It's not empty you just can't access it like that try this: console.log([...dataForm.entries()])
Upvotes: 2
Reputation: 14363
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:
Upvotes: 1