When we combine both PHP and JavaScript functions, we can develop the most dynamic web page or web application. Suppose PHP is a paintbrush that paints a picture then JavaScript provides the color for the paint. So, in this post, we’ll look at how to run JavaScript in PHP.
Run JavaScript in PHP
Let us go through an example where we will call a JavaScript function from PHP but first, we have to link JavaScript with HTML using the script tag of HTML. Within the echo command, PHP treats every HTML element as a string. As a result, we’ll call the JavaScript functions from within the echo command as shown below:
<html lang="en">
<head>
<title>JS and PHP</title>
<script type="text/javascript">
function jsFunction(){
alert('Execute Javascript Function Through PHP');
}
</script>
</head>
<body>
<?php
echo '<script type="text/javascript">jsFunction();</script>';
?>
</body>
</html>
In the output we will see the alert shown below:
We can also execute JavaScript code within the PHP tags by making the script tag and whatever is inside the script tag as a string and then we will send it to the client browser which will execute it. The following code demonstrates this:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS and PHP</title>
<?php
echo '<script type="text/javascript">
alert("Execute Javascript Code");
</script>';
?>
</head>
<body>
</body>
</html>
Conclusion
JavaScript is a client-side programming language that means it deals with the execution of the scripts whereas PHP is a server-side programming language which means it deals with the backend of our web application or web page and is executed by the server. To develop the most dynamic web application or webpage, PHP and JavaScript functions are combined.
In this post, we discussed how to run JavaScript in PHP using two methods.