Okky Okky - 1 year ago 58
HTML Question

Create contact table from JSON file

I am new to JSON.

I was doing a project on HTML, JSON and jQuery recently. Thing I want to achieve now is get data from the JSON file and load it into my table. The data was not loaded into my table.

My json file contact.json

{
"length": 2,
"info": [
{
"name":"Sam",
"email":"[email protected]",
"phone":"789456235"
},
{
"name":"Fred",
"email":"[email protected]",
"phone":"125689564"
}
]
}


My script to load data:

window.onload = function () {
var contacts;
setTimeout(function(){ //pass it an anonymous function that calls foo
loadData("contact");
},2000);
};

function loadData(myfile){
$.getJSON( myfile + ".json", function(data){
console.log(data)
$.each(data, function(index, element){
$.each(element, function(i, item){
$('#contacts').append('<tr><td>' + item.name + '</td><td>'+ item.email +'</td><td>' + item.phone + '</td><td>');
});
});
});
}


My HTML

<body>
<div id="tt" class="easyui-tabs" style="width:400px;height:250px;">
<div title="Home">
<table id='contacts'></table>
</div>
</div>




I copied the whole thing from Create contact table from JSON data

This is the error

TypeError: j is undefined
http://code.jquery.com/jquery-1.4.4.min.js
Line 32


I'm getting the object in the console. but the data is not loaded. How do I fix this problem?

Answer Source

You are passing the relative url to a file into the jQuery.parseJSON function. The API documentation says, that jQuery.parseJSON:

Takes a well-formed JSON string and returns the resulting JavaScript object.

You should first load the content of the json file (maybe with jQuery.getJSON()) and pass the result to the parseJSON function.

Second: You're using different IDs for the table in your HTML and in your JavaScript. "contacts" vs. "contact"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download