简体   繁体   中英

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

 $(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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM