0

I have issue that Ajax request to server and I want to get my all form data and submit it to server. Problem is when I using new FormData(form) is returning an empty object. I done this work before my previous projects and it worked fine. But why not working this time?. I know about .serializeArray but I don't want to use this because of some reasons. The reason is I want to add some files and want to push it to the server.

jquery-version: 3.4.0

Form:

<form id="myForm">
    <input type="email" name="username"/>
    <input type="password" name="password"/>

    <button type="button" id="btn">Submit</button>
</form>

Script:

$(document).ready(function () {
     $('#btn').on('click', function () {
         let formData = new FormData($('#myForm')[0]);
         console.log(formData);
     });
})
kyore
  • 812
  • 5
  • 24

1 Answers1

2

There is entries in your for data object but you are printing formdata object in console. try following to print entries.

You need to iterate loop of entries of formdata to print.

$(document).ready(function () {
  $('#btn').on('click', function () {
    let formData = new FormData($('#myForm')[0]);
    for(var item of formData.entries()) {
      console.log(item[0]+ ', '+ item[1]); 
    }
  });
})

So, if you find entries. so you would need to serialize it to pass it into ajax. or you can create object by entries and pass it using JSON.stringify(data)

var formObject = {};
formData.forEach(function(value, key){
    formObject [key] = value;
});

//In AJAX

data: JSON.stringify(formObject);

And you can get using "POST" or your particular method into server

Ravi
  • 1,312
  • 10
  • 18