A while back I was struggling to explain how a piece of code which showed some PHP within a JavaScript (JS) function could work. As it was only within a comments section, it was difficult to go into full details with examples, so I decided to do a blog post on it.
Just to make it clear, I do not mean that you can run PHP code on the client side. You cannot include a PHP statement within a JS function and hope it will re-evaluate every time the JS function runs. However, if you include your JavaScript within a <script> block on a PHP page, you can use PHP to set static variables within your JS. Essentially you're just generating JavaScript code with PHP.
So this WILL NOT work (or at least, won't make sense):
<script>
function AlertCurrentTime(){
alert("The current time is <?php echo date("h:i:sa") ?>");
}
</script>
This function will popup an alert box with a time displayed. However, the time shown will not be the current time, but that of when the page was loaded. So if the page was loaded an hour earlier, the time will be an hour out. This is as the PHP will run when the page is evaluated by the server, it is then sent to the client with the time hard coded into the alert function. So what the client will see is this:
<script>
function AlertCurrentTime(){
alert("The current time is 07:53:28pm");
}
</script>
However, this does demonstrate how PHP can be used to set values within JavaScript. So this would make sense:
<script>
function AlertPageLoadTime(){
alert("This page was loaded at <?php echo date("h:i:sa") ?>");
}
</script>
The alert will not change after the page has loaded, but it makes sense as the time we output is that of the time the page was loaded.
Or you could do:
<script>
function SetNavigationItems(){
document.getElementById("navigation").innerHtml("<ul><li><a href="index.php" class=''>Home</a></li><li><a href="about.php" class='<?php if ($page == 'about') { echo 'selected'; }?>'>Home</a></li></ul>");
}
</script>
Not sure the situation where you'd want this, but as the page loaded is known at the point of sending it from the server, the "selected" class will be applied to the correct link. If it was the home page, then the client would receive the following:
<script>
function SetNavigationItems(){
document.getElementById("navigation").innerHtml("<ul><li><a href="index.php" class='selected'>Home</a></li><li><a href="about.php" class=''>Home</a></li></ul>");
}
</script>
The client side is not concerned that there is PHP code within the function, as what is delivered to the client does not include any PHP as this was already evaluated server side. The client just sees HTML with a <script> block which the JS engine in the browser then runs.
Hopefully that explains it clearly. Please contact me if you have any questions or feedback.