Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
1  
Your question is very unclear, could you expand exactly on what are you trying to do ? Cheers. –  Shai Mishali Oct 24 '11 at 17:56
 
How about some code? With comments. –  Felix Kling Oct 24 '11 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? –  BDUB Oct 24 '11 at 17:59

5 Answers

up vote 2 down vote accepted
<?php

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

?>

<script type="text/javascript">
  var stuff = <?php print json_encode($stuff); ?>;
  alert(stuff.a); // 1
</script>
share|improve this answer
 
AWESOME! This is exactly what i was looking for, thanks everyone –  BDUB Oct 24 '11 at 18:03
<?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>
share|improve this answer

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.

share|improve this answer

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>
share|improve this answer

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).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.