0

I'm using jQuery templating which is taking JSON data to create a table. This code is working fine. But when I try to create a function around this code and pass JSON data to it which I'm getting from an AJAX request, it shows the values in the console but not in the table. Working code with dummy data is:

var json = [{"class":12,"marks":"500","marks1":"200","marks2":"300"},{"class":11,"marks":"200","marks1":"300","marks2":"400"}]

$.template('kList','<tr title="${class}"><td>${marks}</td><td>${marks1}</td><td>${marks2}</td></tr>');  

for(var i=0; i<json.length; i++){   
    $.tmpl('kList',json[i]).appendTo("#table1")
}

Here is the code where I'm warping the upper code in function and passing the JSON data as a parameter that shows the values in console when I print it with console.log(json) but not filling the table. The JSON parameter is having the same JSON data as in above code.

function dataTable(json){
    console.log(json); // here json values are appearing in the console
    $.template('kList','<tr title="${class}"><td>${marks}</td><td>${marks1}</td><td>${marks2}</td></tr>');  

    for(var i=0; i<json.length; i++){   
        $.tmpl('kList',json[i]).appendTo("#table1")
    }
}

Please help me out because I don't know whats wrong in this code. Thanks in advance.

pilsetnieks
  • 10,330
  • 12
  • 48
  • 60
Sau
  • 2,109
  • 6
  • 21
  • 22

1 Answers1

1

Your json parameter is a string. You should convert it to an object, using $.parseJSON(json).

Take a look at this for conversion detail.

Community
  • 1
  • 1
Reza Owliaei
  • 3,293
  • 7
  • 35
  • 55
  • It is Giving me a response on console as [Object, Object] and i have already used $.parseJSON(json) so the parameter json is the output after using $.parseJSON(json). do you have any other suggestions or do you find anything else wrong in this code? – Sau Apr 18 '13 at 17:33
  • @Sau: So check if `json[0].class` has value and feedback. – Reza Owliaei Apr 18 '13 at 17:36
  • i have tried console.log(json[0].class); and in console its showing me undefined but when i do console.log(json[0]); then it shows all values. can you make this code work i'll be really thankful to you – Sau Apr 18 '13 at 17:59
  • @Sau: Ithink there is something wrong with your json. I don't know what do you mean of " then it shows all values". Write the log. – Reza Owliaei Apr 19 '13 at 09:01
  • @Sau: Regarding your string of json in first part of your answer, I ran a test here, take a look and compare strings of json: http://jsfiddle.net/oliol/zWJeu/ – Reza Owliaei Apr 19 '13 at 09:30
  • I am able to figure it out. you are correct the problem. you are right the problem was with the json. Thanks for your great help.. – Sau Apr 19 '13 at 10:43