Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create contact table from JSON data

I started a demonstration 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. I am new to JSON so it took me a day to get to nothing, the data was not loaded into my table.

Here is my JSON file, 'contact.json':

{
    "length": 2,
    "info": [
        {
            "fullname":"Noob Here",
            "email":"[email protected]",
            "phone":"123456",
            "badgeid": "11111",
        },
        {
            "fullname":"Newbie There",
            "email":"[email protected]",
            "phone":"589433",
            "badgeid": "11112",
        }
    ]
}

My script to load data:

window.onload = function () {
    var contacts;
    setTimeout(loadData(contacts, "contact"), 2000);
    $(contacts.info).each(function(index, element){  
        $('#contacts').append('<tr><td>' + element.fullname + '</td><td>'
            + element.email + '</td><td>'
            + element.phone + '</td><td>'
            + element.badgeid + '</td></tr>');       
    })
};

function loadData(myobject, myfile){
    myobject = $.parseJSON("../data/" + myfile + ".json");
};

Please notice that I may want to load from various JSON file, so loadData have some agruments there. Otherwise, it will parse JSON file directly.

I already had a '#contact' table declared in HTML. The error console said:

Uncaught SyntaxError: Unexpected token.
jQuery.extend.parseJSONjquery.min.js:442
loadDataHomepage.html:23
window.onload

Why is this error appearing? How do I fix this problem?

like image 892
Shinigamae Avatar asked May 18 '26 11:05

Shinigamae


1 Answers

With reference to this post

JSON.parse unexpected character error

I come to know that you parse already parsed JSON

You can replace your script as follows:

    window.onload = function () {
       var contacts;
       $.getJSON('contact.json',function(contacts)
        {
          $(contacts.info).each(function(index, element){  
               $('#contacts').append('<tr><td>' + element.fullname + '</td><td>'
                 + element.email + '</td><td>'
                 + element.phone + '</td><td>'
                 + element.badgeid + '</td></tr>');       
           })  
        });
     };
like image 124
Usman Avatar answered May 20 '26 00:05

Usman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!