How to properly collect form data using new FormData?

  • 0
    I have a custom form. I want to collect all the data in the form and send it to the server for processing, but I came across the fact that when I receive all the data using the new FormData () class, an empty object is returned. How can I get the data correctly and check in the console?

    <form enctype="multipart/form-data" id="userForm" name="userForm">
    	<input type="text" name="FirstName" id="FirstName">
    	<input type="text" name="LastName" id="LastName">
    	<input type="email" name="Email" id="Email">
    	<input type="file" name="file" id="file" multiple accept="application/pdf" >
    	<button class="send" id="send-data">Send</button>

    	$("#send-data").on('click', function(){
    		var formData = new FormData();
    		formData.append('userForm', $('#userForm'));
    		console.log(formData) // empty {}
    JavaScript Anonymous, Oct 17, 2020

  • 3 Answers
  • 0
    formData will always display an empty object, because access to its components is available through special methods. / Form ...

  • 0
    Submitting a pure JavaScript form without using jQuery:

    // По готовности страницы, вешаем на форму обработчик onsubmit инлайново:

    document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('form#userForm').setAttribute('onsubmit', 'event.preventDefault(); form_send(this);');

    // Функция для отправки формы на чистом JavaScript:

    function form_send(form) {
    form.setAttribute('onsubmit', 'event.preventDefault();');
    var url = form.getAttribute('action') + '?nocache=' + new Date().getTime();
    var xhr = new XMLHttpRequest();'POST', url);
    xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
    form.setAttribute('onsubmit', 'event.preventDefault(); form_send(this);');
    if (xhr.status === 200) {
    alert('Форма успешно отправлена, ответ сервера: ' + xhr.responseText);
    else {
    console.log('При отправке формы произошла ошибка, ниже объект с деталями ошибки:');
    alert('При отправке формы произошла ошибка, детали смотрите в консоли.');
    xhr.send(new FormData(form));

    Please note that your form must have the action attribute!
    Naomi Yang

  • 0
    $("#userForm").on("submit", function(e){
    var data = $(this).serialize();

    You can read here about serialize

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!