Okky Okky - 3 years ago 77
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": [

My script to load data:

window.onload = function () {
var contacts;
setTimeout(function(){ //pass it an anonymous function that calls foo

function loadData(myfile){
$.getJSON( myfile + ".json", function(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>');


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

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

This is the error

TypeError: j is undefined
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