Search code examples
javascriptjsonajaxdatatable

Cannot read properties of undefined (reading 'length') show from JSON


I'm getting this error when I try to output data from JSON:

Cannot read properties of undefined (reading 'length')

This is the code I use for fetching data API JSON:

<script>
var myArray = []

$.ajax({
        method:'GET',
        url:'https:/*****/api/customer/',
        success:function(response){
            myArray = response.data
            buildTable(myArray)
            console.log(myArray)
        }
    })
    
    function buildTable(data){
        var table = document.getElementById('myTable')

        for (var i = 0; i < data.length; i++){
            var row = `<tr>
                            <td>${data[i].nama}</td>
                            <td>${data[i].uid}</td>
                            <td>${data[i].pos}</td>
                      </tr>`
            table.innerHTML += row


        }
    }
</script>

This is the JSON form:

[
  {
    "nama": "Mei Nurmita Sari, Amd.Keb",
    "uid": "288-028-23072015",
    "pos": "Director",
    "hp": "",
    "fb": "Mei",
    "ig": "meinu",
    "area": "Kalianda Lampung Selatan ",
    "alamat": "Kalianda-lampung selatan"
  },
  {
    "nama": "Rahma Dhania",
    "uid": "288-334-16092017",
    "pos": "Manager",
    "hp": "081297",
    "fb": null,
    "ig": null,
    "area": null,
    "alamat": "Balikpapan"
  },

Any insight why I got error in length?


Solution

  • Just pass your response and process it. It doesn't have data property.

    Since response.data gives undefined and we are calling undefined.length, it throws an error 'Cannot read properties of undefined (reading 'length')'

     $.ajax({
        method: 'GET',
        url: 'https://jsonplaceholder.typicode.com/users',
        success: function(response) {
            buildTable(response)
        }
     })
    
     function buildTable(data) {
        var table = document.getElementById('myTable')
    
        for (var i = 0; i < data.length; i++) {
            var row = `<tr>
                                <td>${data[i].name}</td>
                                <td>${data[i].username}</td>
                                <td>${data[i].address.city}</td>
                          </tr>`
            table.innerHTML += row
        }
     }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <table id="myTable">
    </table>