2

This is probably an easy question, but I haven't been able to find a complete and specific answer. I create a json object in php with json_encode(), now i just need to get that object in javascript and parse it out. I wanted to do it in the same script, but I can do it another way if need be.

How do i get at this object from javascript?

3
  • 1
    Your question is very unclear, could you expand exactly on what are you trying to do ? Cheers. Commented Oct 24, 2011 at 17:56
  • How about some code? With comments. Commented Oct 24, 2011 at 17:57
  • yeah, i guess its simple enough that im not being clear. I have create d JSON with php. I'm just not sure what i do with the object now, what do i call to be able to parse it in JS? Commented Oct 24, 2011 at 17:59

5 Answers 5

6
<?php

$stuff = array('a' => 1, 'b' => 2);

?>

<script type="text/javascript">
  var stuff = <?php print json_encode($stuff); ?>;
  alert(stuff.a); // 1
</script>
0
2
<?php
    $x = array(1,2,3);
?>

<script type="text/javascript">
   var x = <?php echo json_encode($x);
</script>

would produce

<script type="text/javascript">
   var x = [1,2,3];
</script>
2

If it's all in the same script you and just echo it into the page.

$my_json = json_encode($some_object);
echo '<script type="text/javascript">';
echo "var my_js_obj = $my_json;";
echo '</script>';

Now after that javascript can access the my_js_obj variable.

2

Lets say your php looks like this:

<?php
    $myData = json_encode($some_data);
?>

Then in your javascript you can just assign that php variable to an object like this by echoing the value of that variable.

<script type="text/javascript">
    var myObj = <?=$myData;?>;
</script>
2

I believe you want to do something like this:

<script>
    var jsVar = <?php echo json_encode($phpData); ?>;
</script>

You simply echo the JSON string, since that is a syntax understood by JavaScript (JSON = JavaScript Object Notation).

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.