How to execute a JavaScript Function in PHP?
In this article, we will discuss how to execute a javascript function in PHP. Before that let us discuss what is exactly a javascript function. Then we will go for call a JavaScript function in PHP.
What is a Javascript function?
The Javascript is the client-side script that can add, delete and modify the contents and designs of an HTML.
A function is a set of instructions that have reusability property and it is called by the function name.
Summing up, the javascript function is used to execute or trigger a function from a javascript code block(i.e written between <script> and </sccript>) by any event in HTML block.
Example:-
<html> <body> <script> function add(n1, n2) { return n1 + n2; } document.write(add(12, 10)); </script> </body> </html>
Output:-
22
How to trigger or call the javascript function from PHP
PHP considers every HTML element as strings inside the echo command. So, we will trigger the javascript function calls inside the echo command.
Let us illustrate a simple function call from PHP,
<script> function display() { //display the text document.write("Hello Codespeedy."); } </script> <?php //function is called inside echo command echo '<script>display();</script>'; ?>
Output:-
Hello Codespeedy.
Let us create a javascript function call by a button event i.e. onClick attribute,
<script type="text/JavaScript"> function show_hide() { var x = document.getElementById("parag"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> <?php //show_hide() function is triggered on button click echo "<button onClick='show_hide()'>Show/Hide</button>"; //display this paragraph when button is clicked echo'<p id="parag" style="display:none;">Welcome to Codespeedy.</p>'; ?>
Output:-
In this way, we can execute or call a javascript function in PHP. If you have any doubt, put a comment below,
I tried calling a javascript function using onsubmit within php echo statement and it didn’t work, any ideas on why?