Home > Software engineering >  laravel json response doesnt get printed in datatable
laravel json response doesnt get printed in datatable

Time:02-18

in my web.php I have a model that I turn to json:

Route::get('operatore/ajax',function(PdfDettagli $PdfDettagli){
       return $PdfDettagli::all()->toJson();
    });

In my view I have table:

<table id="table"  style="width:100%">
    <thead>
        <tr>
            <th>nome</th>
            <th>posizione</th>
        </tr>
    </thead>
</table>

and the following jquery:

    script type="text/javascript">
$(document).ready(function(){
    $('#table').DataTable({
        "ajax": "/operatore/ajax",
        "columns": [
        {"data":"nome" },
        {"data":"posizione"}
        ]
    });
});
</script>

It should read the model as json and upload populate the table automatically but It wont do it

The table is this: https://datatables.net/ and in the manual I have read the section about ajax: https://datatables.net/manual/ajax and I think I have done as in the examples but It wont work

If I go in operatore/ajax the response returned is formatted like this:

[{"id":1,"posizione":"operatori\/Giuseppe-Pentangelo\/pdf\/carta-di-identita\/K3hXUVBjUZqBMLgWG2SbMCMdLVK5mcTJTcusSImB.png","nome":"img_avatar.png","id_veicolo":null,"id_operatore":1,"id_categoria_pdf":1,"created_at":"2022-02-15T12:02:53.000000Z","updated_at":"2022-02-15T12:02:53.000000Z"},

I tried model->asArray too and the response it gives is different but it doesnt work neither

Edit: The browser console gives this error:

Uncaught TypeError: f is undefined
    jQuery 17
    <anonymous> http://localhost:8000/pdf:12
    jQuery 13
jquery.dataTables.min.js:49:73
    jQuery 17
        ha
        i
        success
        c
        fireWith
        l
        o
        (Asinc.: EventHandlerNonNull)
    send
        ajax
        sa
        ha
        e
        n
        each
        each
        n
        DataTable
    <anonima> http://localhost:8000/pdf:12
    jQuery 13
        e
        t
        (Asinc.: setTimeout handler)
    l
        c
        fireWith
        fire
        c
        fireWith
        ready
        B
        (Asinc.: EventListener.handleEvent)
    <anonima>
        <anonima>
        <anonima>

CodePudding user response:

DataTable by default expects a response in this format:

{
    "data" : [...]
}

Your endpoint instead returns directly the array of data.

To fix your problem just modify your DataTable configuration from:

"ajax": "/operatore/ajax"

to:

"ajax": {
    "url": "/operatore/ajax",
    "dataSrc": ""
}

Source: https://datatables.net/examples/ajax/custom_data_property.html

  • Related