3 Ways to Execute PHP Function in JavaScript Tutorial

Introduction

In this tutorial, I will show you the 3 Different Effective Ways to execute PHP functions in JavaScript. The tutorial aims to provide the students and new programmers a reference to learn to enhance their programming skills using PHP Language and JavaScript. Here, snippets and sample source code will be provided for a better understanding of using the scripts.

What is PHP Function?

PHP Language comes with over 1000 built-in functions. Developer can also create their own functions to organize their script well and make it reusable. The PHP Function is a block of statements and codes that can be used repeatedly even in a single page load or page execution. The function won't run automatically on page load. Each function will only run when the developer will call the function name to execute on the other part of their scripts.

Technologies Needed

The snippets that I will be providing as an example to demonstrate the effective ways of PHP Function Execution in JS require the following technologies:

  • Web Server that can Run PHP Script i.e. (XAMPP/WAMP)
  • jQuery Library

How to execute PHP Function in JavaScrtip?

PHP can execute easily a JS function but executing a PHP function using JavaScript is kind of tricky due to PHP Scripts being server-side scripts while JavaScript runs on the client side. Although, in some cases, we might need to run PHP Functions using JS to meet our project requirements. To achieve the idea of Executing a PHP Function in JavaScript, we can use the following way:

  • Direct PHP Function Execution in JS
  • PHP Function Execution using JS Fetch API
  • PHP Function Execution using JS jQuery Ajax

These are the effective ways to run your PHP Function in JavaScript. The first way I provided will only work if the parameters or arguments of the PHP Function are statics while the other 2 ways can handle the passing of dynamic data.

Example

Direct PHP Function Execution in JS

Here's an Example snippet for executing a PHP Function in JavaScript. This way it directly executes the PHP function.

  1. /**
  2.   * Direct PHP Exection in JS
  3.   * - only works when the paramaters are static
  4.   */
  5. document.getElementById('testButton1').addEventListener('click', function(e){
  6. var php_func_exec1 = <?= example('1', ['test' => 'Hello World!']) ?>;
  7. console.log(php_func_exec1);
  8. })

The script above executes a PHP Function with static arguments or parameters. This way of execution cannot handle passing any dynamic data. The PHP function will run automatically on page load.

Result

Here's the result of the sample snippet above.

PHP function Execution - Sample 1 Result

PHP Function Execution using JS Fetch API

Below is an example snippet for running the PHP Function in JavaScript using the Fetch API. This way creates a request and receives the response. Using this way, developers can pass dynamic data.

  1. /**
  2. * PHP Exection in JS using Fetch API
  3. * - works when the paramaters are static or dynamic
  4. */
  5. document.getElementById('testButton2').addEventListener('click', function(e){
  6. var param1 = 'This a sample Execution using JS Fetch API',
  7. param2 = `{"a" : "Lorem", "b" : "Ipsum"}`
  8.  
  9. var form = new FormData();
  10. form.append('param1', param1)
  11. form.append('param2', param2)
  12.  
  13. fetch('index.php',{
  14. method:'POST',
  15. body: form,
  16. }).then(response => {
  17. return response.json()
  18. }).then(data => {
  19. console.log(data.parameter1)
  20. console.log($.parseJSON(data.parameter2))
  21. })
  22. })

The snippet submits a request to another page and contains POST Data that can be retrieved and retrieved to the remote page. The script won't run the PHP Function on the current page but instead, the execution will be done at the provided URL remotely and the script will only catch the response of the request.

Result

Here's the result of the sample snippet above.

PHP function Execution - Sample 1 Result

PHP Function Execution using JS jQuery Ajax

The snippet below works the same as the 2nd way I provided. The script requires you to load the jQuery Library to the page.

  1. /**
  2. * PHP Exection in JS using Ajax of jQuery
  3. * - works when the paramaters are static or dynamic
  4. */
  5. document.getElementById('testButton3').addEventListener('click', function(e){
  6. var param1 = 'This a sample Execution using JS jQuery Ajax',
  7. param2 = `{"a" : "Lorem", "b" : "Ipsum"}`
  8.  
  9. $.ajax({
  10. url:"index.php",
  11. method:'POST',
  12. data: {param1:param1, param2: param2},
  13. dataType:'json',
  14. error: error => {
  15. console.error(error)
  16. },
  17. success:function(response){
  18. console.log(response.parameter1)
  19. console.log($.parseJSON(response.parameter2))
  20. }
  21. })
  22.  
  23. })

Result

Here's the result of the sample snippet above.

PHP function Execution - Sample 1 Result

That's it! You can also download the sample program or web application that I created that demonstrates the usage of the 3 effective ways to execute the PHP functions in JavaScript. You can download the source code for free by clicking the download button below this article. Feel free to modify the code to do some more experiments to understand the script more.

DEMO VIDEO

That's the end of this tutorial. I hope this tutorial will help you with what you are looking for and that you'll find this useful for your future and current projects.

Explore more on this website for more Tutorials and Free Source Codes.

Enjoy :)

Add new comment