Reputation: 25
When I write:
alert(<?php echo "33333";?>);
it works.
If I echo a number, it works too. But if I write
alert(<?php echo "346346gj";?>);
it doesn't work.
Can someone tell me why?
Upvotes: 0
Views: 120
Reputation: 324610
To output any kind of PHP value (except resources) directly into JavaScript, use json_encode
.
alert(<?php echo json_encode($myvar); ?>);
$myvar
can be pretty much anything, and it will always work. I alwyas use json_encode
to put a PHP variable into JS.
Upvotes: 0
Reputation: 4012
alert(<?php echo "33333";?>);
will output alert(33333);
. And it's a correct javascript syntax.
alert(<?php echo "346346gj";?>);
will output alert(346346gj);
. It's not a correct syntax.
When you want to alert
a string in javascript you write alert("346346gj");
or alert('346346gj');
So you must replace alert(<?php echo "346346gj";?>);
with one of the following:
alert('<?php echo "346346gj";?>');
alert("<?php echo "346346gj";?>");
alert('<?php echo '346346gj';?>');
alert("<?php echo '346346gj';?>");
alert(<?php echo "'346346gj'";?>');
alert(<?php echo '"346346gj"';?>');
And there are still different conbinations.
Upvotes: 1
Reputation: 195972
Because in javascript, strings need to be in quotes.. so try
alert('<?php echo "33333j";?>');
Upvotes: 0
Reputation: 609
I'm not sure if I understood your problem, but
alert(""+number);
Maybe I misunderstood you. If you want to print php values in JavaScript, you should request them via ajax. "Hardcoding" them isn't the way to go.
Upvotes: 0
Reputation: 181270
Make sure you enclose the generated JS in quotes:
alert('<?= $stringVariable ?>');
Upvotes: 1