3

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":"fred@server.com",
            "phone":"789456235"
        },
        {
            "name":"Fred",
            "email":"fred@server.com",
            "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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Okky
  • 10,338
  • 15
  • 75
  • 122
  • Do you get any JS errors? – Jan Hančič Jan 28 '13 at 09:21
  • 1
    `$.parseJSON("../data/" + myfile + ".json");` parses a JSON string to return an Object; it does not fetch data from you JSON file. For that, you'd need to use $.getJSON("../data/" + myfile + ".json", function(data){ //Parse JSON here }) – kayen Jan 28 '13 at 09:21

3 Answers3

2

$.parseJSON() parses a JSON string to return a JSON object. It does not fetch data from you JSON file. For that, you'd need to use $.getJSON(url, function(data){ //Parse JSON here })

Update your loadData function to:

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

and change your onLoad function to:

window.onload = function () {
    var contacts;
    setTimeout(function(){
        loadData(contacts, "contact");
    }, 2000);
};
kayen
  • 4,838
  • 3
  • 19
  • 20
  • Still I'm not getting data on the page – Okky Jan 28 '13 at 09:28
  • Log the result of the callback and see if you're actually getting any data i.e. put a `console.log(data)` before the `myobject = data` line. – kayen Jan 28 '13 at 09:29
  • Error: useless setTimeout call (missing quotes around argument?) setTimeout(loadData(contacts, "contact")); This is the error I'm getting – Okky Jan 28 '13 at 09:34
  • I'm getting the object in the console. but the data is not loaded – Okky Jan 28 '13 at 10:29
2

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"

Jo David
  • 1,696
  • 2
  • 18
  • 20
  • Your table has an id of "contact" but in jQuery you're trying to access it via "#contacts". ("s" is too much). – Jo David Jan 28 '13 at 09:48
  • I don't want to hard-code. I want to get data from a JSON file – Okky Jan 28 '13 at 09:55
  • Sure, it was just for jsFiddle. I'm sending your json as data to an echo api, so I recieve your data as json (a bit complicated). And I found another bug: In your "append" function you are missing a closing tablerow (). The last should be . – Jo David Jan 28 '13 at 09:56
  • 1
    Here is a fully working code sample hosted on my server. So I can use a json file. http://test.joquery.com/stackoverflow/14558801/ – Jo David Jan 28 '13 at 11:12
2

Try this:

because you have array of info[]

$(function () {
   setTimeout(function(){  //pass it an anonymous function that calls foo
      loadData('contact');
   },2000);
});

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

i have done this on fiddle by creating a var json with all your json values. http://jsfiddle.net/vyTjn/

Jai
  • 74,255
  • 12
  • 74
  • 103
  • Error: useless setTimeout call (missing quotes around argument?) file:///home/sreekeshos/jquery%20ui/index.html.erb Line 16 – Okky Jan 28 '13 at 09:51
  • tried that also. Now i get Error: useless setTimeout call (missing quotes around argument?) http://code.jquery.com/jquery-1.4.4.min.js Line 32 TypeError: j is undefined http://code.jquery.com/jquery-1.4.4.min.js Line 32 – Okky Jan 28 '13 at 09:57
  • I'm getting the object in the console. but the data is not loaded – Okky Jan 28 '13 at 10:29
  • `loadData('contact');` call with `'quotes'` – Jai Jan 28 '13 at 10:34
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/23496/discussion-between-sreekesh-okky-and-jai) – Okky Jan 28 '13 at 10:46
  • k. Still im getting the same error TypeError: j is undefined http://code.jquery.com/jquery-1.4.4.min.js Line 32 – Okky Jan 28 '13 at 10:50
  • have you tested with ugrading the jqeery to latest one. – Jai Jan 28 '13 at 10:52
  • I get the error. TypeError: obj is undefined http://code.jquery.com/jquery-1.8.3.js Line 583 – Okky Jan 28 '13 at 10:58