Why is this error shown that "cannot read property 'length' of undefined" and api data doesn't load

Why is this error shown that "cannot read property 'length' of undefined" and api data doesn't load

sahrishavsahrishav Posts: 1Questions: 1Answers: 0

Table is created but Json data from Api doesn't load.
error:
jquery.dataTables.min.js:62 Uncaught TypeError: Cannot read property 'length' of undefined

What is the error here? help me out

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jason table</title>

<script type="text/javascript" src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

<script>
           fetch('https://jsonplaceholder.typicode.com/todos')
        .then(response => response.json())
        .then(json => console.log(json))
</script>
<script>
    $(document).ready(function () {

        $('#datatable').DataTable({                
            "sAjaxSource": "https://jsonplaceholder.typicode.com/todos",
            "columns": [
                { "data": "user Id" },
                { "data": "id" },
                { "data": "title" },
                { "data": "completed" }
            ]
        });

    });
</script>

</head>

<body>

<div class="container">
    <h1 align="center">Data tables</h1>
    <table id="datatable" class="table table-bordered">
        <thead>
            <tr>
                <th>user Id</th>
                <th>id</th>
                <th>title</th>
                <th >completed</th>
            </tr>
        </thead>
    </table>

</div>

</body>

</html>

Answers

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

    What is you JSON response? Please post an example of it using the browser's network inspector from the XHR tab. Posting a console.log of it won't necessarily show us the structure returned. See this diagnosis section of this technote if you need help.

    Kevin

  • morscodermorscoder Posts: 1Questions: 0Answers: 0
    edited December 2021

    I think you should use { "data": "userId" }, on line 18.
    Note: userId should be without any spaces in between.

Sign In or Register to comment.