I am trying to post my form data using ajax. I am serializing the form data before posting. But at the controller method, it shows null. There is no problem with the form data because I can pass data to controller when I do, var formData_ = $(this).serialize();
$('#i_finish_form').submit(function(e) {
e.preventDefault();
let formData = {
name: $('#i_finish_name').val(),
remarks1: $('#i_bun_num').val()
};
$.ajax({
url: "{{ route('admin_finish_str.store') }}",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
data: JSON.stringify(formData),
success: function(res) {
if (res.status == 200) {
$('#i_add_finish_hid_div_form').toggle();
$('#i_finish_form').trigger("reset");
fetchData();
}
}
});
});
My controller method,
public function store(Request $request)
{
return response()->json(['status'=>'error', 'error'=> $request->n_finish_name]);
}
Json response is null in this case. Why is it so?
serialize()
will return a string like"i_finish_name=some_name&i_bun_num=some_bun_num"
whileJSON.stringify()
will return something like{"i_finish_name":"some_name","i_bun_num":"some_bun_num"}
which have to be interpreted accordingly.$request->json('n_finish_name')
JSON.stringify( formData)
, the return statement in controller is showing null. If the data is passed to controller it should not show null although the interpretation may be incorrect.data: formData
. jQuery will serialize it automatically.