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?
5 Answers 5
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.
Comments
Make sure you enclose the generated JS in quotes:
alert('<?= $stringVariable ?>');
Comments
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.
1 Comment
Because in javascript, strings need to be in quotes.. so try
alert('<?php echo "33333j";?>');
Comments
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.
1 Comment
why? not how?