Datatable with Data from Symfony 5.1 Controller via Ajax

Datatable with Data from Symfony 5.1 Controller via Ajax

Lara20Lara20 Posts: 10Questions: 4Answers: 0

I have a datatable, but since I have got lots of data, the loading causes issues. I therefore decided the data should be loaded via AJAX, but I do not get the data shown. I have 3 version below how I return data, but none work. How do I have to format the data, how do I return the data from the controller and how would I use it in the datatable?

 $('#all-po-items').DataTable({
    'columnDefs': [

        // These are the column name variables that will be sent to the server

        { "data": "firstname",   "targets": 0 },
        { "data": "lastname",   "targets": 1 },
        { "data": "username",  "targets": 2 },
    ],
    // Server-side parameters
    "processing": true,
    "serverSide": true,
    // Ajax call
    "ajax": {
        "url": "/members/load-items",
        "type": "POST",
          dataSrc: "data"
    },


    // Classic DataTables parameters
    "paging" : true,
    "info" : true,
    "searching": true,
    "pageLength": 10,
    "order": [[4, 'asc']],

   // My Controller

     public function getAllItemsJSON()
    {
       $em = $this->getDoctrine()->getManager();
       $members= $em->getRepository(Member::class)->getAllMembers();
       return new JsonResponse($members); // tried this
       return new JsonResponse(["data" =>$members]); // tried this
       return new Response(json_encode(["data" => array($members)]), 200, ['Content-Type' => 'application/json']); //tried this
     }

This question has accepted answers - jump to:

Answers

  • kthorngrenkthorngren Posts: 21,172Questions: 26Answers: 4,923
    Answer ✓

    How do I have to format the data, how do I return the data from the controller and how would I use it in the datatable?

    The Ajax manual discusses all these points. Let us know if you have any questions.

    Kevin

  • Lara20Lara20 Posts: 10Questions: 4Answers: 0

    I would suppose that my error is in the way I return the data from Symfony. It looks like an array of objects, so do I have to format it first in the controller and if so, how would I return it? I really struggle with this.

  • kthorngrenkthorngren Posts: 21,172Questions: 26Answers: 4,923
    Answer ✓

    You also have server side processing enabled. Your server script is expected to follow the Server Side Processing Protocol. I'm not familiar with Symfony. You may want to find a tutorial, like this one to start with.

    Kevin

  • Lara20Lara20 Posts: 10Questions: 4Answers: 0

    Thank you. I think I might have it. I do have to format the Object first in the controller and return that. I do still have some problem with a date etc, but I might figure it out. Thank you to both of you. I will Update my question with the answer when it is finally running.

This discussion has been closed.