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

Alexandre Khoury
4,0625 gold badges40 silver badges59 bronze badges
asked Jul 7, 2012 at 16:07
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.

answered Jul 7, 2012 at 16:21
Sign up to request clarification or add additional context in comments.

Comments

1

Make sure you enclose the generated JS in quotes:

alert('<?= $stringVariable ?>');
answered Jul 7, 2012 at 16:09

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.

answered Jul 7, 2012 at 16:09

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";?>');
answered Jul 7, 2012 at 16:12

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.

answered Jul 7, 2012 at 16:23

1 Comment

Bach Fuc said why? not how?

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.