-1

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?

0

5 Answers 5

1

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.

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

Comments

1

Make sure you enclose the generated JS in quotes:

alert('<?= $stringVariable ?>');

Comments

0

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

If he has already the value in php before generating the Javascript, why should he use Ajax?
0

Because in javascript, strings need to be in quotes.. so try

alert('<?php echo "33333j";?>');

Comments

0

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

Bach Fuc said why? not how?

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.