0

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);
4
  • Can you print the value you are trying to parse? It's probably mis-formatted. Commented Apr 22, 2014 at 0:28
  • What is the exact generated js code? Copy-paste it as-is from the page body Commented Apr 22, 2014 at 0:28
  • it could be that the JSON is not formatted correctly. you might want to show the JSON that $latLongJson is supposed to be Commented Apr 22, 2014 at 0:31
  • JSON is correct, i used json_encode to prepare that JSON and validated it on JSONLint Commented Apr 22, 2014 at 0:31

1 Answer 1

3

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

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

3 Comments

Ok, so the thing is i am trying to create a PHP API of my service. The endpoint gives me a JSON. I want to consume that JSON using JS code. Both on same domain.
i didn't even see the + signs.
@CodeMonkey Judging from your edit it looks like $latLongJson is empty. Make sure that $latLongJson = $dbUrl->getCoordinates($id); is before the var json_obj = ... line.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.