Search code examples
phpjsonajaxlaravelpost

Cannot access data of deserialized json


I'm using ajax to send data to my controller, here's how I do it

var formData = JSON.stringify( $('#SubmitForm').serializeArray() );
$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});
$.ajax({
  type: 'POST',
  data: {formData},
  url: '{{route("fileController.sendFiles")}}',
  success: function(response) {
    console.log(response);
  },
  error: function(response){
    console.log(response);
  }
});

Here's the route

Route::post('/sendFiles', ['uses' => 'FileController@sendFiles'])->name('fileController.sendFiles');

And the controller

public function sendFiles(Request $request)
{
  //$data = json_decode($request->input('formData'), true);
  //return $request->input('allFiles');
  $data = json_decode($request->input('formData'), true);
  return $data['allFiles'];
}

However, I get this error

"message": "Undefined index: allFiles"

When I check the contents of $request, I can see that allFiles array is clearly there, but how do I access it? P.S. I've tried changing the second param when decoding to false, there's no difference.

$request data array


Solution

    • First of all your request data is simple array of objects. So you cannot index it with "allFiles".
    • Second since we have multiple objects with attribute name="allFiles[]", what you can do is filter those objects and return the values of it. (I don't know how are you going to use it, but this is how the code looks)
    public function sendFiles(Request $request)
    {
      //$data = json_decode($request->input('formData'), true);
      //return $request->input('allFiles');
      $data = json_decode($request->input('formData'), true);
      //filter all allFiles object
      $allFiles = array_filter($data, function($obj){ 
                 if(isset($obj->name)){
                    return $obj->name=="allFiles[]";
                 }
                 return false;
               });
      //get values for all the filtered objects
      $allFilesValues = array_map(function($obj){ return $obj->value; }, $allFiles);
      return $data['allFiles'];
    }
    

    Let me know if this works for you.