1

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?

6
  • Can you show your HTML as well? Keep in mind that serialize() will return a string like "i_finish_name=some_name&i_bun_num=some_bun_num" while JSON.stringify() will return something like {"i_finish_name":"some_name","i_bun_num":"some_bun_num"} which have to be interpreted accordingly.
    – newelski
    Commented yesterday
  • Why are you using JSON instead of URL-encoded data?
    – Barmar
    Commented yesterday
  • I don't use Laravel myself, but AI told me that you should use $request->json('n_finish_name')
    – Barmar
    Commented yesterday
  • @newelski The problem I am facing is that using 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. Commented yesterday
  • @Barmar you mean var formData_ =$(this).serialize(); ? Using this, I have two questions 1 what if we don't need to post all the input elements of the form 2. what if we need to do some manipulation on input data before posting the form. At such cases how to use var formData_ =$(this).serialize(); ??? Commented yesterday

1 Answer 1

1

After doing many searches, I got success in passing data to the controller method, just need to add curly braces for the data parameter.

I passed data as

data: JSON.stringify({formData})

Now in the controller method, to retrieve data what I did is:

$finish->remarks1 = $request->json('formData.remarks1');

Thank you everyone for help!!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.