I have a php file in which i have added JS inside echo. I want to use php function inside that JS scope now, how can i do that:
<?php
echo '<script>
<?php
function message() {
echo "You will be redirected";
}
?>
setTimeout(<?php message();>?,3000);</script>';
?>
PHP will execute first, on the server, so you would have to code it in a .php file, to ensure the server runs it through PHP, then have it embed the PHP in the JavaScript like so:
<script>
function message(){
alert("<?= $phpMessage ?>");
location.href = "http://www.example.com" /* The URL you would like the user to go to next */;
}
setTimeout(message,3000);
</script>
Assuming you want to display a message from PHP, you may embed it in an alert statement as <?= $phpMessage ?>. This will be awkward for your users.
A more graceful solution would be to use session storage to pass a message to the next page.
On the page that is receiving the data and needs to send a message, the first PHP command, before any output is sent should be session_start(). A message may be saved in a session variable with $_SESSION['message'] and it will be available for the next script, like so:
one.php (first page)
<?php session_start(); $_SESSION['message'] = 'My Message';
two.php (second page)
<?php session_start(); echo $_SESSION['message']; unset($_SESSION['message']); ?>
Notice that the second script must use unset to clear the message.
No matter what you do, JavaScript can't execute your PHP in the context of a page. Based on your example, I don't think you'd want to do that in PHP anyway.
If you just want to output a message before redirecting a user, JavaScript alone is the right tool for the job:
<script>
function message() {
document.write("You will be redirected");
}
setTimeout(message,3000);
</script>
I'm trying to think of a scenario in which it would make sense to mix PHP and JavaScript like you asked about, but I can't.
However, if you really insist...
<?php
function message() {
return "You will be redirected";
}
echo '
<script>
setTimeout(() => document.write("' . message() . '"), 3000);
</script>
';
?>
Tested at https://repl.it/GF2E/0
Note that the JavaScript arrow function syntax is supported by all current browsers.