views:

53

answers:

2

why does this script show empty alert box. I am trying to use php value in javascript

<script type="text/javascript">
 alert(<?php echo count($myorder) ?>); </script> 

thanks

+5  A: 

Probably because you are not encapsulating the PHP output into quotes (JavaScript should give you an error on that?), and the echo statement is missing a mandatory optional semicolon.

Try

<script type="text/javascript">
 alert("<?php echo count($myorder); ?>"); </script> 
Pekka
both are correct (missing the ; in the echo, and no quotations around the alert, however it functions without issue in firefox and IE as is - so not 100% sure that's it.
David Larrabee
A semi-colon is not required at the end of a `<?php ?>` block.
Daniel Wright
@Daniel you're right - I wasn't sure and didn't have the time to test. Corrected my answer, cheers.
Pekka
+2  A: 

remove the javascript - and just echo the variable to the screen, what does the value show?

looking at the sample, even though as the previous answer mentioned you missed the ; at the end of the echo, and you didn't quote the alert, it still actually works at least in firefox and IE8. The count should always return a value even on a null value or a non-array, so not 100% sure but would be interested to see what it shows in php only.

just for sanity sake try this....

<?php echo "before | " . count($myorder) . " | after";?>

and what is the output....

if the value is not an array, is null, or is an array with zero entries it should be

before 0 after

and if it has elements it would be whatever the count is, obviously.

David Larrabee