Possible Duplicate:
How to call a JavaScript function from PHP?
Can I add a javascript alert inside a PHP function? If yes, how?
Possible Duplicate:
How to call a JavaScript function from PHP?
Can I add a javascript alert inside a PHP function? If yes, how?
Yes, you can, though I 100% guarantee this isn't what you want or what you mean:
<?php
function do_alert($msg)
{
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
?>
<html><head><title>Hello</title></head>
<body>
<h1>Hello World, THis is my page</h1>
<?php
do_alert("Hello");
?>
</body>
</html>
The browser runs the Javascript, the server runs the PHP.
You could also echo Javascript from your server (without HTML) and then include that script into your page by dynamically creating a <script>
tag containing that Javascript. This is essentially creating Javascript on the fly for injection into your page with the right headers etc.
If you want to trace some PHP script execution, then you can use trigger_error()
to create a log entry, or you could write a trace()
function to store strings in a buffer and add them to a page.
If you want to trace Javascript, See Firebug for Firefox.
PHP Headers API Documentation
On-demand Javascript at Ajax Patterns
Assuming that what you mean is that you want an alert to pop up from the browser when the server reaches a certain point in your php code, the answer is "no".
While the server is running your php code, there's no contact with the browser (until the response starts coming back). There are situations in which a server may be streaming content back to the browser, and in such a case it'd be possible to have some agreed-upon convention for the server to mark the content stream with messages to be alerted out immediately, but I don't think that's what you're asking about here.
To explain; PHP is compiled at the server and the result is plain HTML. Therefore alerts and such cannot appear while compiling is a silent process.
If you want to show an alert in the HTML generated by PHP;
<?php
echo '<script type="text/javascript"> alert(\'Hi\'); </script>
?>
Yes, if you send Javascript code with alert
to a html page from PHP.
No, if you want to call alert
just by executing server side code and not sending JS to client browser.
echo "<script type='text/javascript'>alert('alert text goes here');</script>";
But i don't know how it can be useful because it will work only on the client side. If you want to debug your code you can simply print it on the screen, but if you use the alert take care of quotes because they can break the javascript part.
You can output a Javascript alert() within a PHP function in at least two ways:
A) Return it:
function sendAlert($text) {
return "<script type='text/javascript'>alert('{$text}');</script>";
}
B: Output it directly:
function echoAlert($text) {
echo "<script type='text/javascript'>alert('{$text}');</script>";
}