Jachym
Jachym

Reputation: 485

Format of JSON output not working

I have a problem with JSON format. My goal is to generate a highcharts chart with data pulled from php via ajax. I finally got it all working except there is some problem with the format of the data output.

So, in my data.php file I have:

$result = array();
$result['name'] = '2013';
$x = mysqli_query($con,"
    SELECT Logdatetime, Temp
    FROM alldata 
    LIMIT 12"
);

while($r = mysqli_fetch_array($x)){
$result['data'][] = $r['Temp'];
}

print json_encode($result, JSON_NUMERIC_CHECK);

When I tried it, the output looked like this:

{"name":2013,"data":[-1.4,-1.4,-1.3,-1.3,-1.3,-1.3,-1.3,-1.2,-1.3,-1.2,-1.2,-1.2]}

Then in my main page I have the AJAX call like this:

$.ajax({
    url : 'data.php',
    datatype : 'json',
    success : function (json) {
        alert(json);
        options.series[0].name = json['name'];
        options.series[0].data = json['data'];
        chart = new Highcharts.Chart(options);
    },
});
}

I put the alert there to check the data and the result is the same as the one above produced by PHP, so it seems correct. However, there must be some problem with parsing the data contained in "data" and "name" - in other words, if I put:

options.series[0].name = json['name'];

nothing is inserted (alert produces "undefined"), if I put for example:

options.series[0].name = json[1];

Then I get the name as the second character. This means that there must be some problem with the interpretation of the JSON output by AJAX, but I wasnt able to figure out what the problem is.

Upvotes: 1

Views: 608

Answers (2)

Pointy
Pointy

Reputation: 413747

The jQuery $.ajax property is "dataType", not "datatype". If you don't set the data type properly, you get the raw string as the parameter to the callback.

$.ajax({
    url : 'data.php',
    dataType : 'json', // <--- note the capital "T"
    success : function (json) {
        alert(json);
        options.series[0].name = json['name'];
        options.series[0].data = json['data'];
        chart = new Highcharts.Chart(options);
    }, // <--- GET RID OF THIS COMMA
});

Upvotes: 2

scrowler
scrowler

Reputation: 24405

You need to put data into that second line as well... Try this:

options.series[0].name = json.name;
options.series[0].name = json.data[0];

Upvotes: 0

Related Questions