2 votes

Uncaught TypeError: Cannot read property 'length' of undefined [json, ajax and DataTables]

I don't get to show the data in my table.

With the following index sending json data from my table:

public function index(Request $request)
    {
    if ($request->ajax()) {
        $modelos = Modelos::all();
        return response()->json($modelos);
    }
    return view('modelos.index');
}

Then in my view when I try to display:

    $(document).ready(function() {
        $('#mytable').DataTable( {
            "ajax": "/modelo",
            "columns": [
                { "data": "marca" },
                { "data": "modelo" },
                { "data": "part_number" },
                { "data": "coste" },
                { "data": "caracteristicas" },
            ]
        } );

 <body>
<a href="{!!URL::to('/modelo/create')!!}" class="create">Nuevo</a>
<table id="mytable" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Marca</th>
            <th>Modelo</th>
            <th>Part Number</th>
            <th>Coste</th>
            <th>Características</th>
        </tr>
    </thead>

    <tfoot>
        <tr>
            <th>Marca</th>
            <th>Modelo</th>
            <th>Part Number</th>
            <th>Coste</th>
            <th>Características</th>
        </tr>
    </tfoot>
</table>



But I get the error on the console:

Uncaught TypeError: Cannot read property 'length' of undefined

The json received is as follows:

[{"id":1,"marca":"HP","modelo":"EliteBook 840","part_number":"44G57TH","coste":1,"caracteristicas":"4GB RAM 256GB SSD","created_at":"2017-04-16 14:36:58","updated_at":"2017-04-16 14:36:58"}]

If you step a ajax created manually as the following I have no problem and shows me perfectly the data in my table:

{
"data": [
{
    "marca": "Prueba",
    "modelo": "modelo",
    "part_number": "12354",
    "coste": "0",
    "caracteristicas": "Nose"
}]

}

The only difference I see, is that the former does not include "data:" and this, yes, but I don't know how to spend it the same way.

Thanks in advance.

1voto

I found the solution in another question in this forum: solution . Affecting my code as follows:

 $(document).ready(function() {
        $('#mytable').DataTable( {
            "ajax": {
                "url": "/modelo",
                "dataSrc": ""
                },
            "columns": [
                { "data": "marca" },
                { "data": "modelo" },
                { "data": "part_number" },
                { "data": "coste" },
                { "data": "caracteristicas" },
                {{--{ "data": "salary" }--}}
            ]
        } );
 

I hope it helps you. Thank you!

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X