Table of Contents
Introduction
Whatever we see on our website, it is either saved within HTML or being fetched from a table. The HTML has a script file attached with it which calls backend, where SQL codes are written. These SQL codes interact with database. In this article we will learn how to call different functions in a PHP file from JavaScript. There might be multiple use cases, scenarios and ways to call a function of PHP from JavaScript, we will be showing one that can be easily called via any AJAX call.
How to call different functions in a PHP file
The very first thing that is required in a PHP file is the declaration of $_POST in the header of php:
The code will look something like this:
<?php header("Access-Control-Allow-Origin:*, Origin, X-Requested-With, Content-Type, Accept"); echo $_POST["method"](); ?>
Here we have just added a header that will help us in AJAX calls from JavaScript and an echo that will help us to call any function defined within the PHP file.
Now, we can add a function inside the PHP file which can return simply a message whenever it is called.
//simple function example function readCall(){ echo 'PHP Call is successful'; }
Full Code
<?php header("Access-Control-Allow-Origin:*, Origin, X-Requested-With, Content-Type, Accept"); // header('Content-Type: application/json'); echo $_POST["method"](); //simple function example function readCall(){ echo 'PHP Call is successful'; } ?>
Calling different functions in PHP from frontend
The above PHP function can be called from UI as shown below:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type = "text/javascript"> function script(){ // AJAX call $.ajax({ url: "http://localhost:81/test/server.php", type: "POST", data: { method: "readCall" }, success: function (response) { alert(response); }, error: function (request, error) { alert(request); } }); } </script> </head> <body onload="script()"> <h1>HTML Content</h1> </body> </html>
0 Comments