Home > Software engineering >  Unable to get the the data from AJAX request to Laravel controller and work with it?
Unable to get the the data from AJAX request to Laravel controller and work with it?

Time:04-12

I am making the following AJAX call:

var dataURL = canvas.toDataURL();
var token = "{{ csrf_token() }}";

$.ajax({
      type: "POST",
      url: "{{route('site.image.store')}}",
      data: {
        imgBase64: dataURL,
      },
      processData: false,
      contentType: false,
      headers: {'X-CSRF-TOKEN': token},
    }).done(function(response) {
      console.log('done');
});

And my controller is:

public function store(Request $request)
{
    dd($request->all());
}

However I am getting and empty array []. How can I access the imgBase64 data and work with it in the controller?

I am not submitting a form to make the post request I am just using the canvas data.

CodePudding user response:

The reason it does not work for you is that Laravel uses the Content-Type header of the request to determine how to parse the input data.

If you specify contentType: false in your request, you're specifically building the AJAX request in such a way that no Content-Type header will be sent.

That way Laravel does not know how to parse the body of the request.

So to resolve your issue you have to specify the correct contentType for your request. The default for jQuery's $.ajax() function is application/x-www-form-urlencoded; charset=UTF-8 (see documentation)

  • Related