0

I'm following this example from amCharts but I can't load JSON from PHP file, this what have I done:

AmCharts.loadJSON = function(url) {
     if (window.XMLHttpRequest) {
         var request = new XMLHttpRequest();
     } else {
         var request = new ActiveXObject('Microsoft.XMLHTTP');
     }
     request.open('GET', url, false);
     request.send();
     return eval(request.responseText);
};


AmCharts.ready(function() {
   var chartData = AmCharts.loadJSON('chart.php');
   console.debug(chartData);
 });

But I always get:

return eval(request.responseText);
Uncaught SyntaxError: Unexpected string 

I have googled but all solutions include jQuery, and it's recommended not to use eval.

3
  • eval is for evaluate a string as a script, its not for a json object. Commented Mar 23, 2014 at 14:54
  • 1
    Use JSON.parse() to parse JSON - not eval() ... Commented Mar 23, 2014 at 14:54
  • console.log(request.responseText)? Commented Mar 23, 2014 at 14:56

2 Answers 2

3

Use the JSON property, which is a part of the window object (unless you're using an old browser).

JSON.parse(request.responseText);

Here is a shim for IE7 and other old browsers.

To turn an object in to a JSON string, use JSON.stringify({ foo: 1 });

Do determine whether if you need the shim or not, you could simpy do

if(JSON){
    // safe to use the JSON object
}

Based on your comment, you have some invalid syntax:

[{ "date": "22/03/14", "value1": 15, "value2": 12.1 "value3": 15 "value4": 15 }]

Some properties are missing commas to separate them. It should look something like this:

[{ "date": "22/03/14", "value1": 15, "value2": 12.1, "value3": 15, "value4": 15}]

Note that what you posted is an array. There is no need to use JSON.parse(). The only valid thing as far as JSON is concerned here would be to stringify it to a JSON string. But I don't think that's what you're after here.

However, if it's the evauled string that you provided me with, then eval() should be replaced with JSON.parse().

Sign up to request clarification or add additional context in comments.

6 Comments

Yes, but even with JSON.parse i get in output Uncaught SyntaxError: Unexpected string
@BojanVidanovic Could you provide me with the string that you're trying to parse?
[{ "date": "22/03/14", "value1": 15, "value2": 12.1 "value3": 15 "value4": 15 }, {...}]
@BojanVidanovic as MamaWalter pointed out, the array contains invalid object literals. I'll update my answer
Yep, now it's working. Don't know how i missed that. Thanks for help!
|
0

The error

Uncaught SyntaxError: Unexpected string

is possibly due to wrong data in responseText varible.

I was also facing problem with eval() function. Then i debugged (use F12 key) and found that data in responseText is not correct.

After correcting data in responseText, eval() function is working fine for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.