0

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> 

2 Answers 2

5

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> 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
A semi-colon is not required at the end of a <?php ?> block.
@Daniel you're right - I wasn't sure and didn't have the time to test. Corrected my answer, cheers.
2

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.

Comments

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.