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
var usernameSelected = document.getElementById['username'];
var usernameWarning = document.getElementById['usernameResult'];
usernameSelected.addEventListener['keyup', function[] {
var request = new XMLHttpRequest[];
var url = "//www.jenrenalcare.com/upload/poanchen.github.io/sample-code/2016/10/16/how-to-create-simple-rest-api-in-php-and-call-them-in-js/checkIfUsernameExist.php";
var params = "username=" + usernameSelected.value;
request.open['POST', url, true];
request.setRequestHeader["Content-type", "application/x-www-form-urlencoded"];
request.onreadystatechange = function[] {
if [request.readyState === XMLHttpRequest.DONE] {
if [request.status === 200] {
var response = JSON.parse[request.response];
if [response.result] {
usernameWarning.innerHTML = "The username you typed has been used!";
}else{
usernameWarning.innerHTML = "You may freely use this username!";
}
}
}
};
request.send[params];
}];
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
$[document].ready[function [] {
var usernameSelected = $['#username'];
var usernameWarning = $['#usernameResult'];
usernameSelected.keyup[function[] {
var url = "//www.jenrenalcare.com/upload/poanchen.github.io/sample-code/2016/10/16/how-to-create-simple-rest-api-in-php-and-call-them-in-js/checkIfUsernameExist.php";
var formData = {
'username' : usernameSelected.val[]
};
$.ajax[{
type : 'POST',
url : url,
data : formData,
dataType : 'JSON',
encode : true,
success: function [response, status, xhr] {
if [response.result] {
usernameWarning.html["The username you typed has been used!"];
}else{
usernameWarning.html["You may freely use this username!"];
}
},
error: function [xhr, status, error] {
usernameWarning.html["Something went wrong!"];
}
}];
}];
}];
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
{{ return_message }}