1
<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() ?

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
dweerwerw
  • 15
  • 3

5 Answers5

5

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.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
4

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>
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
3

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.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
0

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>';

Tim Withers
  • 12,072
  • 5
  • 43
  • 67
0

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();">';
}
Kiley Naro
  • 1,749
  • 1
  • 14
  • 20