Failing to display json array in html table

Blake Tucker

I am using a php script to produce a json array. The json array is retrieved by a jquery ajax script which then tries to read it and embed it in an html table. However, I'm stuck since it keeps producing 'undefined' data in the table. I want to display the information of the json array in my table after the ajax returns successfully. Please help...

The JSON Array format

[{"fullname":"Frank Robsinga","gender":"Male","email":"n\/a","phone":"n\/a","status":"1"}]

The javascript

<script>
$("#lookup").click(function() {

var key = $("#search").val();

$.ajax({
    type : 'POST',
    url : 'scripts/search-user-script.php',
    data : {
        key : key
    },
    success : function(obj) {

        $("#usersdata").html("");
        for (var i = 0; i < obj.length; i++) {
            var tr = "<tr>";
            var td0 = "<td>" + (i + 1) + "</td>";
            var td1 = "<td>" + obj[i]["fullname"] + "</td>";
            var td2 = "<td>" + obj[i]["gender"] + "</td>";
            var td3 = "<td>" + obj[i]["email"] + "</td>";
            var td4 = "<td>" + obj[i]["phone"] + "</td>";
            var td5 = "<td>" + obj[i]["status"] + "</td></tr>";
            $("#usersdata").append(tr + td0 + td1 + td2 + td3 + td4 + td5);

        }

    }
});
// .ajax
});
</script>

A screenshot of the results enter image description here

guradio

var obj = [{
  "fullname": "Frank Robsinga",
  "gender": "Male",
  "email": "n\/a",
  "phone": "n\/a",
  "status": "1"
}]

for (var i = 0; i < obj.length; i++) {
  console.log(obj[i].fullname)
  console.log(obj[i].gender)
  console.log(obj[i].email)
  console.log(obj[i].phone)
  console.log(obj[i].status)
}
<table id='usersdata'></table>

you have to . also remove [""] like obj[i].status

you ajax should look like :

$.ajax({
    type : 'POST',
    url : 'scripts/search-user-script.php',
    dataType:'json',
    data : {
        key : key
    },
    success : function(obj) {

        $("#usersdata").html("");
        for (var i = 0; i < obj.length; i++) {
            var tr = "<tr>";
            var td0 = "<td>" + (i + 1) + "</td>";
            var td1 = "<td>" + obj[i].fullname + "</td>";
            var td2 = "<td>" + obj[i].gender + "</td>";
            var td3 = "<td>" + obj[i].email + "</td>";
            var td4 = "<td>" + obj[i].phone + "</td>";
            var td5 = "<td>" + obj[i].status + "</td></tr>";
            $("#usersdata").append(tr + td0 + td1 + td2 + td3 + td4 + td5);

        }

    }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related