Daniel Franklin
Daniel Franklin

Reputation: 1

How can I use a php variable in javascript

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

Upvotes: 0

Views: 118

Answers (9)

CrystalShardz
CrystalShardz

Reputation: 49

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.

Upvotes: 0

Pupil
Pupil

Reputation: 23958

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

Upvotes: 0

Ram Sharma
Ram Sharma

Reputation: 8809

Change

var test = <?php $test ?>

to

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

Upvotes: 0

Umair Hamid
Umair Hamid

Reputation: 3557

You can use

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

below the definition of $test.

Upvotes: 0

voondo
voondo

Reputation: 2583

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

Upvotes: 0

Frederik Spang
Frederik Spang

Reputation: 3454

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

Or using shorthand echos, like this:

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

Upvotes: 0

georg
georg

Reputation: 214959

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)

Upvotes: 2

Mahmood Rehman
Mahmood Rehman

Reputation: 4331

try like this :

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

Upvotes: 0

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

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

Upvotes: 0

Related Questions