1

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: 
};

1 Answer 1

1

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;
?>
Sign up to request clarification or add additional context in comments.

7 Comments

The rendered output shows name: , and errors in Firefox with SyntaxError: expected expression, got ',' name : ,
What is actually in $myjQueryVar ?
I've edited my question. I think it answers your question?
@rwkiii: $myjQueryVar is not a PHP but a JavaScript variable in your code, so it is empty!
I don't understand. I am using json_encode and echoing the output to $myjQueryVar in the rendered script code. I have one other PHP variable I am able to use in jQuery - it works fine, but it is not output within a heredoc.
|

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.