BDUB
BDUB

Reputation: 387

pass JSON object from php to javascript in the same script

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?

Upvotes: 2

Views: 5495

Answers (5)

Jan-Henk
Jan-Henk

Reputation: 4874

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

Upvotes: 2

Brian Glaz
Brian Glaz

Reputation: 15676

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>

Upvotes: 2

Chris Cherry
Chris Cherry

Reputation: 28554

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.

Upvotes: 2

Marc B
Marc B

Reputation: 360672

<?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>

Upvotes: 2

aw crud
aw crud

Reputation: 8891

<?php

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

?>

<script type="text/javascript">
  var stuff = <?php print json_encode($stuff); ?>;
  alert(stuff.a); // 1
</script>

Upvotes: 6

Related Questions