How to run JavaScript from PHP?

JavaScript is the customer side prearranging language and PHP is the server side prearranging language. JavaScript is utilized as customer side to check and confirm customer subtleties and PHP is server side used to connect with information base. In PHP, HTML is utilized as a string in the code. To deliver it to the program, we produce JavaScript code as a string in the PHP code.

PHP is a server-side programming language which implies it executes at the server end and it will return the HTML code. Then again, Javascript is customer side (runs at customer program) prearranging language, which is utilized typically to approve customers subtleties.

How to run JavaScript from PHP?

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>

Output:

eevibes

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>

Output:

eevibes

Example 3: JavaScript Function – DOM Manipulation (in same PHP file)

<?php
    echo "<div id='demo'></div>";
?>
<script type="text/JavaScript">
 
// Function is called, return 
// value will end up in x
var x = myFunction(11, 10);   
document.getElementById("demo").innerHTML = x;
 
// Function returns the product of a and b
function myFunction(a, b) {
    return a * b;             
}
</script>

Output:

110

JavaScript is most popular for site page advancement however it is likewise utilized in an assortment of non-program conditions. You can gain JavaScript from the beginning by following this JavaScript Tutorial and JavaScript Examples.

PHP is a server-side prearranging language planned explicitly for web improvement. You can gain PHP starting from the earliest stage by following this PHP Tutorial and PHP Examples.

Also ReadHow to Install Chrome in Ubuntu?

Leave a Reply

Your email address will not be published.