Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
<html>
<script type="text/javascript">
function show_alert()
{
  alert("I am an alert box!");
}
</script>
<body>
<?php
$x = 8;

if($x ==10){
  echo "Hi";
}
else{
  echo 'show_alert()';
}
?>

</body>
</html>

How do I get the echo to output the value of show_alert() ?

share|improve this question

5 Answers

up vote 5 down vote accepted

Change

echo 'show_alert()';

to

echo '<script>show_alert()</script>';

so that the browser knows to treat show_alert() as a function call and not regular HTML text.

share|improve this answer
3  
Two seconds ahead of me. That's what I get for writing an explanatory sentence. – Michael Berkowski Aug 24 '11 at 18:50
@Michael, Less talking, more providing technically correct but unenlightening answers :) – Mike Samuel Aug 24 '11 at 18:52

You need to wrap it in a script tag:

if($x ==10){
  echo "Hi";
}
else{
  echo '<script type="text/javascript">show_alert();</script>';
}

Note, this will not wait until the page has finished loading to call show_alert(). The alert will be displayed as soon as the browser reaches this point in the page rendering, which may be otherwise incomplete behind the alert box. If you want it to wait until the whole page is loaded, place the condition to be called in <body onload>

<body <?php if ($x != 10) {echo 'onload="show_alert();"';} ?>>
   <?php 
     if ($x == 10)
     {
         echo "Hi!";
     }
   ?>
</body>
share|improve this answer

If you mean call showAlert() when the browser renders/evaluates that line:

echo '<script type="text/javascript">show_alert();</script>';

If you mean get the value of showAlert() in PHP, you can't - PHP is a server-side language.


This:

echo 'show_alert()';

will simply print "showAlert()" on the page, unless you have already opened a <script> tag.

share|improve this answer
+1 For the explanatory sentence – NullUserException Aug 24 '11 at 18:51

I think you may be confused about the difference between client side and server side code. HOWEVER, if you are using the two correctly, and you want to make it appear:

echo '<script type="text/javascript">show_alert();</script>';

share|improve this answer

It depends largely upon when you want the show_alert() javascript function to be called. Guessing by the PHP code that you're using, I am going to assume that you want the javascript function to be called as soon as the page loads, in which case you might want to use PHP before the body loads, and add an "onload" attribute event handler to your body tag:

if($x ==10){
   echo '<body>';
}
else{
  echo '<body onload="show_alert();">';
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.