CodeMonkey
CodeMonkey

Reputation: 2295

Using PHP Json in Javascript

I am trying to get a PHP JSON variable in my JS function:

    var json_obj = jQuery.parseJSON ( ' + <?php echo $latLongJson; ?> + ' );

The PHP code which is fetching me the latLongJson variable is :

<?php
    $latLongJson = $dbUrl->getCoordinates($id);
    print_r($latLongJson);
?>

I am able to print latLongJson variable using PHP. But console.log for json_obj says it is undefined.

JS Code

<script>
    //<![CDATA[
    var json_obj = jQuery.parseJSON ( ' + <?php echo $latLongJson; ?> + ' );
    //var json_obj = 1;
    //]]>
    console.log(json_obj);
</script>

Generated JS Code:

//<![CDATA[
var json_obj = jQuery.parseJSON ( ' +  + ' );
//]]>
console.log(json_obj);

Upvotes: 0

Views: 183

Answers (1)

Paul
Paul

Reputation: 141829

Think about what ' + <?php echo $latLongJson; ?> + ' becomes when $latLongJson is valid.

For example, say that $latLongJson contains the string {"foo": "bar"}, then you are calling:

jQuery.parseJSON ( ' + {"foo": "bar"} + ' );

When you just want:

jQuery.parseJSON ( '{"foo": "bar"}' );

You can remove the + to get it to work, but you don't normally* need to parse JSON in Javascript anyway. If you know that $latLongJson contains valid JSON, you can just do:

var json_obj = <?php echo $latLongJson; ?>;

*There is an exception

Upvotes: 3

Related Questions