1

I have a js inside a jsp from where I want to send a json in another js.

In jsp the console.log(html_out); prints the json right.

  $.ajax({
     //ajax code
     },
        async: true
    })
    .done(function(html_out) {
        console.log(html_out);
        drawTable(html_out);

    })

Output for console.log(html_out):

{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }

But, in js the json doesn't put the data right inside the table i want to put them. The console.log(rowData); displays :

 { 
 t
 i
 t
 l
 e
 :
 "
 h
 ...
 ...

Here is my code in the js that i want to print my json:

function drawTable(data){

for (var i=0; i<data.length; i++){
    drawRow(data[i]);
}
}
function drawRow(rowData) {
   console.log(rowData);
var row = $("<tr />")
$("#farmacyDataTable").append(row);
row.append($("<td>" + rowData.title + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));

}
nancy
  • 175
  • 1
  • 8
  • 2
    You need to parse JSON first, obviously that `data` is a string. – dfsq Jan 08 '16 at 12:49
  • Possible duplicate of [How do I iterate over a JSON structure?](http://stackoverflow.com/questions/1078118/how-do-i-iterate-over-a-json-structure) – Aleksandr M Jan 08 '16 at 12:49
  • how can I parse it in my situation? I tried but can't do it – nancy Jan 08 '16 at 12:52
  • 1
    Like @dfsq says, you're data array is still a string. Use the function $.parseJSON to actually make your data into a json object. – Glubus Jan 08 '16 at 12:52
  • @Dfsq it's obvious because you have seen this problem before – Ruan Mendes Jan 08 '16 at 12:53
  • @JuanMendes it's obvious because when iterating it is actually printing the '{' characters as well, which is javascript syntax. – Glubus Jan 08 '16 at 12:54
  • @Glubus Where in my code I have to use this function? – nancy Jan 08 '16 at 12:57
  • @nancy check out the answer posted, you need to change the data you're getting inside drawtable into json, so anywhere before you start iterating over data do something like this data = $.parseJSON(data); Also if you're getting errors, it might be because your logged json isn't valid json, it needs extra {} around the entire thing with "'key' :" in front of each object for it to be valid json – Glubus Jan 08 '16 at 12:59

3 Answers3

1

As mentioned by dfsq, you have to parse the JSON string into a JavaScript object, right now you are iterating over the string

$.ajax({
   //... ajax code
   async: true, // Not needed, it default to async: true, async:false is deprecated
   // If you add the line below, you don't need to parse the response
   // dataType: 'json'
})
.done(function(html_out) 
    drawTable(JSON.parse(html_out));
})

If you correctly set the MIME type for the response (on the server), you will not need to call JSON.stringify

http://api.jquery.com/jquery.ajax/

dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • I'm quite sure `JSON.parse` is redundant, as jQuery should do it behind the scene automatically with properly configured `$.ajax`. Also `done` is deprecated I think. And `async: true` is not necessary. – dfsq Jan 08 '16 at 13:08
  • @dfsq It will be an object if the server is correctly sending the MIME type for JSON. Otherwise, it default to a string. – Ruan Mendes Jan 08 '16 at 14:09
  • @dfsq The deprecated methods are `success,error,complete`, done is not deprecated. See http://api.jquery.com/jquery.ajax/ `Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.` – Ruan Mendes Jan 08 '16 at 14:11
  • Doesn't matter what content-type is. If `dataType: 'json'` is set then jQuery will try to parse it. – dfsq Jan 08 '16 at 14:44
  • @dfsq Yeah, but the OP didn't, that's exactly why I posted the documentation from `jQuery` – Ruan Mendes Jan 08 '16 at 15:02
  • My point is that proper solution in this case is `dataType: 'json'` and not `JSON.parse(html_out)`. But whatever. – dfsq Jan 08 '16 at 15:13
  • @dfsq It's up to the OP: they can specify the dataType, they can parse it, or they can fix their configuration, that's what jQuery lets you do. I'm not going to specify how the OP should do it, but I did a note that it's also an option – Ruan Mendes Jan 08 '16 at 15:35
1
var parsed = JSON.parse(html_out);
drawTable(parsed);

Please take a look at the JSON.parse MDN page for browser compatibility.

Arman Ozak
  • 2,304
  • 11
  • 11
  • You should always offer an explanation along with a solution so the OP understands why they would need to call `JSON.parse` – Ruan Mendes Jan 08 '16 at 14:13
0

I made some corrections to your code, you can play with it here: https://jsfiddle.net/mzf4axc0/

var jsonData=[{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }];

function drawTable(data){
    for (var i=0; i<data.length; i++){
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
  console.log(rowData);
  var row = $("<tr /><td>" + rowData.title + "</td><td>" + rowData.name +  "</td>" + "</tr>");
  $("#farmacyDataTable").append(row);
}

$(document).ready(drawTable(jsonData));
Jiri Cap
  • 156
  • 6