Call php api from javascript

This work perfectly for me:

To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.

I found a way:

This for JavaScript:

function callPHP(expression, objs, afterHandler) {
        expression = expression.trim();
        var si = expression.indexOf("(");
        if (si == -1)
            expression += "()";
        else if (Object.keys(objs).length > 0) {
            var sfrom = expression.substring(si + 1);
            var se = sfrom.indexOf(")");
            var result = sfrom.substring(0, se).trim();
            if (result.length > 0) {
                var params = result.split(",");
                var theend = expression.substring(expression.length - sfrom.length + se);
                expression = expression.substring(0, si + 1);
                for (var i = 0; i < params.length; i++) {
                    var param = params[i].trim();
                    if (param in objs) {
                        var value = objs[param];
                        if (typeof value == "string")
                            value = "'" + value + "'";
                        if (typeof value != "undefined")
                            expression += value + ",";
                    }
                }
                expression = expression.substring(0, expression.length - 1) + theend;
            }
        }
        var doc = document.location;
        var phpFile = "URL of your PHP file";
        var php =
            "$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
            "$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
            "set_include_path($folder);include $fileName;" + expression + ";";
        var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
        $.ajax({
            type: 'GET',
            url: url,
            complete: function(resp){
                var response = resp.responseText;
                afterHandler(response);
            }
        });
    }


This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:



So, your PHP code remain equals except return values, which will be echoed:



I suggest you to remember that jQuery is required:
Download it from Google CDN:


or from Microsoft CDN: "I prefer Google! :)"


Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!

The choice is to you!


Now you finished! I just tell you how to use callPHP function. This is the JavaScript to call PHP:

//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
            'num1' : 1,
            'num2' : 2
        },
            function(output) {
                alert(output); //This to display the output of the PHP file.
        });

In this post, we are going to talk about how we can create a simple REST API in PHP and call them in JavaScript using various technologies. For example, using XMLHttpRequest, jQuery AJAX and AngularJS AJAX. In order to create a simple REST API that might actually be used in practice, we are going to use WordPress API namely the username_exists() function that allow us to check if the username exist in a WordPress database and return true if the username exists or false otherwise. For simplicity, we are going to skip on how to build a WordPress site, and go straight to writing the PHP code for the simple REST API.

PHP code for simple REST API

  // Include the wp-load.php so that we can use username_exists() function in WordPress API
  $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
  require_once( $parse_uri[0] . 'wp-load.php' );

  $data = array();
  $username = sanitize_text_field($_POST['username']);

  if (username_exists($username)) {
    $data["username"] = $username;
    $data["result"] = true;
  }else {
    $data["username"] = $username;
    $data["result"] = false;
  }

  // return all our data to an AJAX call
  echo json_encode($data, JSON_PRETTY_PRINT);

source code hosted on GitHub
Live link hosted on JenRenalCare.com

An example of a response from this simple REST API is as follows, or you may click the link above. (Notice that the request would have to be POST, you may test it out using Postman)

  { "username": "poanchen", "result": false }

Now we have a really simple REST API that allows us to check if the username exist or not. This is especially useful in registration form where we allow the user to know if the username exist or not before they submit the form. This can be done using JavaScript. First example that I would like to show is using XMLHttpRequest. Here is a sample code that does the job.

Code for using XMLHttpRequest

   type="text" id="username" name="username" placeholder="username">
   id="usernameResult">

source code hosted on GitHub
Live link hosted on JenRenalCare.com
Try it on CodePen

As the user type, they may immediately see if the username is taken or not. An example of taken username is test.

Another example that I would like to show is using jQuery AJAX. Here is a sample code that does the job.

Code for using jQuery AJAX

     type="text" id="username" name="username" placeholder="username">
     id="usernameResult">

source code hosted on GitHub
Live link hosted on JenRenalCare.com
Try it on CodePen

As the user type, they may immediately see if the username is taken or not. An example of taken username is test as mentioned earlier.

Another example that I would like to show is using AngularJS AJAX. Here is a sample code that does the job.

Code for using AngularJS AJAX

   ng-app="usernameApp" ng-controller="usernameController">
     type="text" ng-model="username" ng-keyup="usernameKeyup()" placeholder="username">
    

{{ return_message }}

source code hosted on GitHub
Live link hosted on JenRenalCare.com
Try it on CodePen

As the user type, they may immediately see if the username is taken or not. An example of taken username is test as mentioned earlier.

Wrapping Up

Hopefully this guide has given you the confidence to do many other things with querying a simple REST API using various technologies like pure JavaScript with XMLHttpRequest or AJAX call via jQuery or AngularJS AJAX. Please go ahead and take a look at the code and add more things to it to make it do more interesting things. I am sure that you will start getting the hang of it while you add those new things. I hope that this post has helped you and good luck to you!

Resources

I’ll try to keep this list current and up to date. If you know of a great resource you’d like to share or notice a broken link, please let us know.

WordPress APIs

  • WordPress APIs « WordPress Codex by WordPress

REST API

  • REST API concepts and examples by WebConcepts (YouTuber)
  • Do you know what a REST API is? - SitePoint by Sam Deering

XMLHttpRequest

  • XML DOM - HttpRequest object - W3Schools by W3Schools

jQuery AJAX

  • jQuery.ajax() - jQuery API Documentation by jQuery

AngularJS AJAX

  • AngularJS Documentation for $http by AngularJS

Can you call PHP from JavaScript?

The reason you can't simply call a PHP function from JavaScript has to do with the order in which these languages are run. PHP is a server-side language, and JavaScript is primarily a client-side language.

Does JavaScript interact with PHP?

JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the browser, we produce JavaScript code as a string in the PHP code.

How do I call a PHP function from another file?

To call a function from another file in PHP, you need to import the file where the function is defined before calling it. You can import a PHP file by using the require statement. To call the greetings() function from another file, you need to import the library.

How do I pass variables and data from JavaScript to PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];