1

I am using a JSON string to pass a variable in JavaScript from PHP :

while( $row = mysql_fetch_array($result) )
        {
                $tmp = array('id'=>$row['id'], 'alert_type_id'=>$row['alert_type_id'], 'deviation'=>$row['deviation'], 'threshold_low'=>$row['threshold_low'], 'threshold_high'=>$row['threshold_high']) ;
                $settings[] = $tmp ;
        }

        echo '{"data":'.json_encode($settings).'}' ;

in Javascript, i am using the following snippet :

console.log( result ) ;                
var json = eval('('+ result +')') ;

and what appears in the Console is the following error :

1{"data":[{"id":"1","alert_type_id":"1","deviation":null,"threshold_low":"20","threshold_high":"80"}]}

SyntaxError: Expected token ')'

Could you please help me overcome this issue please ? Many Thanks.

user690182
  • 269
  • 1
  • 8
  • 20

3 Answers3

2

In your PHP, you probably want to use json_encode for encoding all of your data:

$result = array(
  'data' => json_encode($settings)
);

echo json_encode($result);

Second, in your javascript, eval is rarely (never) a good idea. From Douglas Crockford's style guide:

The eval function is the most misused feature of JavaScript. Avoid it.

Instead, you probably want to use JSON.parse() to rebuild the result returned by the server:

console.log(result) ;                
var resultObj = JSON.parse(result);
console.log(resultObj);

If your code is still broken, you might want to double-check your PHP to make sure it isn't spewing out any output beyond the json_encode statement.

rjz
  • 16,182
  • 3
  • 36
  • 35
1

Something is outputting a "1" in front of your json string. Javascript is unable to resolve that properly during eval().

davidethell
  • 11,708
  • 6
  • 43
  • 63
0

Well that line of code isn't valid.

Write in the console:

'(1{"data":[{"id":"1","alert_type_id":"1","deviation":null,"threshold_low":"20","threshold_high":"80"}]})'

As this is what you're passing to the eval function. I should give you the same error.

If you want to save that string in a variable you need to adjust it a bit:

eval('var x =' + result);

Anyway It looks like you're doing something wrong, check again why do you need ti use the "evil" eval.

gdoron
  • 147,333
  • 58
  • 291
  • 367