3

$(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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for you great support. Please Clear me one thing. if here i upload a file or then how can i get the all the file value with file object, then what should i use var formData = new FormData(this)[0]; or var formData = new FormData(this);
Why do you keep wanting to add the [0]?? Send the whole object! If there are file inputs it will include files also
yes . if The Html Like This <form action="" method="POST" id="color_changer_form"> <input type="text" id="color_code" name="color_code"> <input type="file" id="file" name="image"> <button type="submit" id="color_submit" class="btn btn-success">Save Change</button> </form>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.