rwkiii rwkiii - 4 months ago 19
jQuery Question

PHP array to jQuery array within <<<EOT

I have some PHP that outputs some jQuery code using

<<<EOT
. The PHP contains an array I want to use inside the jQuery, but can't get it to work.

The problem is with the jQuery array is always
null
. I've tried several ways of doing

PHP:

$myPHPVar = array( 'name' : 'data1', 'description' : 'data2');

function confirmation() {

global $myPHPVar;

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

var $confirmation = <<<EOT
<script>
function postToFeed() {
var obj = {
name: $myjQueryVar['name'],
description: $myjQueryVar['description']
};

feed.post(obj);
}
</script>

<div><a href="#" onClick="postToFeed()">Share your results!</a></div>
EOT;

return $confirmation;
}


In the code above,
$myjQueryVar
is always null. I've cut out irrelevant code and free-handed most of the above, but I think it accurately represents the logic of my code on this issue.

Is it apparent from the code above what I'm doing wrong?

EDIT

In my code example above, I wrote:

$myPHPVar = array( 'name' : 'data1', 'description' : 'data2');


I don't know if it makes a difference, but the actual code I am using is:

$myPHPVar = array(
"name" => 'Odio a',
"description" => 'Phasellus viverra vel odio a laoreet.'
);


Still, after following @Jan suggestion below, the rendered output is:

function postToFeed() {
var obj = {
name: ,
description:
};

Jan Jan
Answer

Use curly brackets inside the heredoc:

var obj = {
  name: '{$myjQueryVar['name']}',
  description: {$myjQueryVar['description']}
};

Additionally, as said in the comments, you are mixing JavaScript and PHP variables. This one works (using $myPHPVar instead):

<?php
$confirmation = <<<EOT
<script>
function postToFeed() {
    var obj = {
      name: '{$myPHPVar['name']}',
      description: '{$myPHPVar['description']}'
    };

    feed.post(obj);
}
</script>

<div><a href="#" onClick="postToFeed()">Share your results!</a></div>
EOT;

echo $confirmation;
?>