Can't get value of input field when using ajax FormData() in Laravel

Viewed 1437

$(document).on('submit', '#color_changer_form', function(e) {
  e.preventDefault();
  var colorCode = $('#color_code').val();
  var formData = new FormData(this)[0];
  $.ajax({
    headers: {
      'X-CSRF-Token': "{{csrf_token()}}"
    },
    type: "POST",
    url: "{{route('color.store')}}",
    data: formData,
    async: false,
    success: function(data) {
      console.log(data)
    },
    cache: false,
    contentType: false,
    processData: false
  });
});
<form action="" method="POST" id="color_changer_form">
  <input type="text" id="color_code" name="color_code">
  <button type="submit" id="color_submit" class="btn btn-success">Save Change</button>
</form>

Controller snippet:

public function store(Request $request){
    return response()->json($request->all());
}

When I try to get the whole form data using the jQuery AJAX FormData() method, I get an empty array.

In need to use this FormData() because in the near future I have to upload an image using the form data.

1 Answers

Send the whole formData object

Change:

 var formData = new FormData(this)[0];

To

 var formData = new FormData(this);

If there are no files involved it is simple to use serialize() also

$.ajax({
  headers: {
    'X-CSRF-Token': "{{csrf_token()}}"
  },
  type: "POST",
  url: "{{route('color.store')}}",
  data: $(this).serialize(),
  success: function(data) {
    console.log(data)
  }

});

Never use async:false. it is a terrible practice and is deprecated

Related