Register Login

How to Call a JavaScript Function from PHP?

Updated Feb 27, 2021

PHP is a server-side programming language which means it executes at the server end and it will return the HTML code. On the other hand, Javascript is client-side (runs at client browser) scripting language, which is used normally to validate clients details.

Example 1: Call Javascript function declared in the head section

In this example we are calling Javascript function “jsFunction” which is declared in the head section.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Call JS Function</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>

Run Code

Output:

How to call a JavaScript function from PHP

You can execute Javascript through PHP by calling javascript code/function as a string in PHP and send it to the client browser to execute. See example 2.

Example2: Execute javascript code through PHP

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Call JS Code</title>
<?php
echo '<script type="text/javascript">
alert("Execute Javascript Code");
</script>';
?>
</head>
<body>
</body>
</html>

Run Code

Output:

How to call a JavaScript function from PHP


×