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

georg
216k57 gold badges325 silver badges401 bronze badges
asked Dec 16, 2013 at 11:43

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)

answered Dec 16, 2013 at 11:45
Sign up to request clarification or add additional context in comments.

Comments

0
var test = '<?php echo $test; ?>'
answered Dec 16, 2013 at 11:43

1 Comment

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

try like this :

var test = '<?php echo $test ?>';
answered Dec 16, 2013 at 11:43

Comments

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

Or using shorthand echos, like this:

var test = '<?= test;?>';
answered Dec 16, 2013 at 11:45

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); ?>
answered Dec 16, 2013 at 11:46

Comments

0

You can use

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

below the definition of $test.

answered Dec 16, 2013 at 12:04

Comments

0

Change

var test = <?php $test ?>

to

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

user987339
10.7k8 gold badges45 silver badges48 bronze badges
answered Dec 16, 2013 at 11:44

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 ?>";
answered Dec 16, 2013 at 11:45

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.

answered Dec 16, 2013 at 12:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.