-2

Trying to parse a json response from URL in javascript.

Here is what the response looks like

   {"data":[{"version":"7.4.0","startDate":"2016-12-   12","totalSessions":"6208723","totalCrashes":"2944","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-11","totalSessions":"4979676","totalCrashes":"2378","crashRate":"0.048"},{"version":"7.4.0","startDate":"2016-12-10","totalSessions":"534913","totalCrashes":"208","crashRate":"0.039"},{"version":"7.4.0","startDate":"2016-12-09","totalSessions":"309564","totalCrashes":"147","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-08","totalSessions":"255597","totalCrashes":"162","crashRate":"0.063"},{"version":"7.4.0","startDate":"2016-12-07","totalSessions":"21379","totalCrashes":"12","crashRate":"0.056"}]}

I can dump the json output using

var crash = $.post('http://localhost/crash_stats.php', function(data2) {
    $('#show-list').html(data2); //shows json

});

Then I tried to parse it using

document.getElementById("placeholder").innerHTML=data2.data[0].version

also tried

obj = JSON.parse(crash);
console.log(obj.data2[0].version);

But no luck.

teej2542
  • 577
  • 3
  • 10
  • 27

1 Answers1

0

You should tell jQuery that the AJAX function returns JSON, then it will parse it automatically for you.

var crash = $.post('http://localhost/crash_stats.php', function(data2) {
    $("#placeholder").text(data2.data[0].version);
}, 'json');

Or you can call JSON.parse() yourself.

var crash = $.post('http://localhost/crash_stats.php', function(data2) {
    var data = JSON.parse(data2);
    $("#placeholder").text(data.data[0].version);
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I also figured out another way using the following function Get(yourUrl){ var Httpreq = new XMLHttpRequest(); // a new request Httpreq.open("GET",yourUrl,false); Httpreq.send(null); return Httpreq.responseText; } var json_obj = Get("http://localhost/metricsapi/api/crash_stats.php?version=7.4.0"); var jsonObj = JSON.parse(json_obj); But I am getting the following error "Uncaught SyntaxError: Unexpected token" – teej2542 Dec 14 '16 at 16:27
  • You shouldn't use synchronous AJAX, it's deprecated. Learn proper Javascript programming. – Barmar Dec 14 '16 at 16:46
  • Your URL is wrong. It should be `var json_obj = Get("//localhost/metricsapi/api/crash_stats.php?version=7.4.0");` – Barmar Dec 14 '16 at 16:47
  • Since you left out `//`, it thinks that `localhost/` is a directory name, not the server name. – Barmar Dec 14 '16 at 16:48
  • Actually everything worked, The problem was that when I encoded the json output in php, I needed to add a header('Content-Type: application/json') – teej2542 Dec 14 '16 at 20:53
  • You don't need that if you're parsing `Httpreq.responseText`. – Barmar Dec 14 '16 at 20:55