Reputation: 15
<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() ?
Upvotes: 1
Views: 197
Reputation: 270677
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>
Upvotes: 4
Reputation: 55324
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.
Upvotes: 3
Reputation: 1779
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();">';
}
Upvotes: 0
Reputation: 12059
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>';
Upvotes: 0
Reputation: 120516
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.
Upvotes: 5