0

If I have created a variable in php, say $test, how can I set a variable in javascript, say var test, to be equal to it.

I have already tried var test = <?php $test ?>

9 Answers 9

2

I guess

var test = <?php echo json_encode($test) ?>

The naive way var test = '<?php echo ($test) ?>' will fail if $test contains quotes or newlines, let alone is not of the string type (e.g. array, object)

Sign up to request clarification or add additional context in comments.

Comments

0
var test = '<?php echo $test; ?>'

1 Comment

Try it with $test="bug's".
0

try like this :

var test = '<?php echo  $test ?>';

Comments

0
var test = '<?php echo $test; ?>';

Or using shorthand echos, like this:

var test = '<?= test;?>';

2 Comments

Try it with $test="bug's".
"Since PHP 5.4.0, <?= is always available." Unless told otherwise, I believe it's safe to assume, atleast PHP 5.4.0 is used.
0
var test = <?php echo json_encode($test); ?>

Comments

0

You can use

<pre>
var test = '<?php echo $test?>';
</pre>

below the definition of $test.

Comments

0

Change

var test = <?php $test ?>

to

var test = <?php echo $test; ?>

Comments

0

You are missing two things:

var test = <?php $test ?>

1) Echo statement.

2) Single Quotes around PHP snipplet.

So, the corrected code should be:

var test = "<?php echo $test ?>";

2 Comments

Try it with $test="bug's".
@thg435, please suggest the answer then:)
0

Within your page where you want your PHP to output to type:

var MyJavascriptVariable = <?php echo $myPHPVariable; ?>

Advise NOT to use short tags () as this can be disabled by webhosts and may break your code.

Comments

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.