Trieu Quang Phuc
Trieu Quang Phuc

Reputation: 25

Error call php in javascript

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

Answers (5)

Niet the Dark Absol
Niet the Dark Absol

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

Alexandre Khoury
Alexandre Khoury

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

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

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

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

Upvotes: 0

Daniel
Daniel

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

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

Make sure you enclose the generated JS in quotes:

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

Upvotes: 1

Related Questions