Fenrir Von Der Nebelungs
V.

Calling PHP from JavaScript

V.1.1 Introduction to AJAX

This subsection discusses how to use JavaScript to call server-side scripts. One method to interacting with PHP routines from JavaScript is through AJAX. AJAX stands for Asynchronous JavaScript and XML. AJAX is included with most modern browsers. It includes the "XMLHttpRequest" JavaScript object and its functions which can be used to make asynchronous calls to scripts, including PHP scripts.

The following topics are covered in this section:

  • a basic example of how to call PHP from JavaScript using AJAX;
  • passing variables from PHP to JavaScript for GET requests;
  • passing variables from PHP to JavaScript for POST requests;
  • and receiving variables from JavaScript with PHP.

V.1.2 Prerequisites

The topics covered in this section require a basic knowledge of programming PHP and JavaScript as covered by "PHP and JavaScript". A general knowledge of object based programming languages is also assumed. Finally a working knowledge of basic HTML script is required.

The sofware packages for Apache (or another server program) and PHP must be installed and running as discussed in "Setting up a Local Linux Server". In addition a web browser, such as Chrome, is required.

V.1.3 Contents

V.1 Overview
V.1.1 Introduction to AJAX
V.1.2 Prerequisites
V.1.3 Contents
V.2 Calling PHP from JavaScript with AJAX
V.2.1 Overview
V.2.2 An Elementary Example
V.2.3 The AJAX and How It is Configured
V.2.4 The PHP Script
V.3 Passing Variables
V.3.1 Intro
V.3.2 Returning Variables from PHP to JavaScript
V.3.3 Passing Variables from JavaScript to PHP for "GET" requests
V.3.4 Passing Variables from JavaScript to PHP for "POST" requests
V.3.5 Recieving Variables Passed by "POST" and "GET"
V.3.6 The Example Scripts

V.2.1 Overview

This section discusses a simple example of using AJAX to call a PHP function from JavaScript. The code and its functions are discussed starting with the entry function, "testGet()". Then the creation and configuration of the AJAX "XMLHttpRequest" object is covered.

The "XMLHttpRequest" object uses a "request method" to call another script, in this case, a PHP script. The configuration of this object includes the request method used to call it and the code that executes when the request for the server side script execution finishes. The function that rewrites the HTML element and displays the message returned by the PHP is part of the code that executes when the request finishes.

V.2.2 An Elementary Example

The following script, "testAJAX.js", demonstrates calling a simple PHP function from AJAX.

function dumpScriptOutput(dumpText){
document.getElementById("forDump").innerHTML = dumpText;
}
function testGet(){
var req=false;
try{ //try ... catch(e) is used for error handling
req=new XMLHttpRequest();
}catch(e){// if the browser does not support the XMLHttpRequest function then return false.
return false;
}
req.onreadystatechange = function(){
if(req.readyState==4){
if(req.status==200){
dumpScriptOutput(req.responseText);
}else{
alert("Failed to open script");
}
}
};
req.open("GET", "simpAJAX.php", true);
req.send();
}

It can be invoked from the ".html" file, "testAJAX.html":

<!DOCTYPE html> 
<html> 
    <head> 
        <script type="text/javascript" src="testAJAX.js"></script> 
    </head> 
                                
    <body> 
        <div id="forDump"></div> 
    </body> 
                                
    <script type="text/javascript"> 
        testGet();
    
    </script> 
                            
</html>

The "testGet()" function defined in "testAJAX.js" is called by "testAJAX.html" when the browser opens this HTML script. This function in turn calls and executes the PHP script "simpAJAX.php", which sends a message back to the JavaScript to be displayed by the browser.

V.2.3 The AJAX and How It is Configured

In "testGet()", the "XMLHttpRequest" AJAX object "req" is created with the line:

req=new XMLHttpRequest();

The "req" object is then configured with the lines:

req.onreadystatechange = function(){
...
}

These lines define what will happen when the "readyState" property of the "req" object changes. Specifically the "anonymous" function defined by the code between the brackets, after "function()", is called when the "readyState" changes.

The line:

req.open("GET", "simpAJAX.php", true);

Configures the "XMLHTTPrequest" object to call the server-side script, "simpAJAX.php". The first parameter of "XMLHttpRequest.open(...)" determines what type of HTTP request method is being used. Common request methods include "GET" and "POST" to retrieve and send data respectively. The second parameter of the "open" function is the URL of the page, or server-side script, that is being requested. The third and final parameter sets whether the request is asynchronous. If this parameter is set to true, then code written in "testAJAX.html" after "testGet()" is called may execute before the results from the "XMLHttpRequest.open" command are posted. For further discussion of asynchronous vs. non-asynchronous execution of requests to the server, see the comments at the end of this section.

The line:

req.send();

submits the request as setup by the "XMLHttpRequest" "open" function.

After the script "simpAJAX.php" finishes, it changes the "readyState" of the "XMLHttpRequest" object. This causes the function defined by "req.onreadystatechange = function(){...}" to execute. With the line, "if(req.readyState==4)", this function first checks if the "readyState" property of the "XMLHttpRequest" object has changed to "4". The code "4" indicates that the request is complete. Next it checks the "response code" of the HTTP server response with the line: "if(req.status==200)". "200" is the "OK" code. If the response indicated failure, then it posts an error-message alert. If the server returned "OK" then the line:

dumpScriptOutput(req.responseText);

executes. This line calls the function the JavaScript function, "dumpScriptOutput(...)".

The function, "dumpScriptOutput(...)" is defined at the beginning of "testAJAX.js" and writes the text string that it is passed to the HTML page displayed in the browser. "req.responseText" returns a text string. The "XMLHttpRequest" function, "responseText" retrieves from the "XMLHttpRequest" object the string that was returned by the script (simpAJAX.php) it called. If a PHP script is called by the "XMLHttpRequest" object, anything printed by the PHP script using the "echo", "print" or "printf" commands will be sent to the "responseText" of the "XMLHttpRequest" object.

V.2.4 The PHP Script

The PHP script called by the function "testAJAX.js" is defined as follows:

<?php
echo "This php script was sucessfully called by AJAX";
?>

All this script does when called is echo a line which then is sent to the "responseText" of the AJAX object, to be printed by the JavaScript code in the browser. This script can be saved as "simpAJAX.php" in the "/var/www/" directory.

V.3.1 Intro

AJAX objects can return data from and pass data to server-side PHP scripts. The syntax for returning variables from PHP to JavaScript is the same irregardless of the type of AJAX request. However the syntax for sending variables from JavaScript to PHP is dependant on whether the request method is "GET" or "POST".

This section covers three main topics:

  • how PHP scripts return complex variables to the JavaScript code using string "objects";
  • how variables are passed from JavaScript to PHP for "GET" requests;
  • and how variables are passed from JavaScript to PHP for "POST" request.

V.3.2 Returning Variables from PHP to JavaScript

Variables can be returned by imbedding them into a string which is passed back to the AJAX object by the server-side script. Variables returned from server-side scripts have already been discussed in the last section; data printed by the PHP script can be found in the "responseText" of the XMLHttpRequest object after the script completes.

Arrays can be passed from PHP scripts back to the client-side JavaScript functions using JSON formated strings. The JSON formated string is then converted by the JavaScript code into a JavaScript object. JSON is covered by in the section "Basic JavaScript" of Chapter II, "PHP and JavaScript". The following scripts demonstrate passing a simple array from PHP back to the client-side JavaScript as an object.

The first script, "jsonDemo.php", is:

<?php
    $test_arr = array("name"=>"spruce blue", "height"=>10.5, "hmax"=>40);
    $ret_json_str = json_encode($test_arr);
    echo $ret_json_str;
?>

In this script the PHP array is defined by the first line, and converted into a JSON encoded string by the second line using the PHP function "json_encode". "json_encode" takes a PHP array as input, "$test_arr", and returns a string which represents the array in JSON format, "$ret_json_str". The third line returns it as a string to XMLHttpRequest object.

The second script, "testAJAXJSON.js", is essentially the same as "testAJAX.js" except that "jsonDump.php" is called instead of "simpAJAX.php" and the function "dumpScriptOutput" is rewritten.

Error: could not call javascript function.

In the function "dumpScriptOutput" the line:

array_ret = JSON.parse(retText);

converts the JSON formated string, "retText", that was returned by the PHP script, to a JavaScript array object. The next line reads two variables from this new array, "array_ret", into the string "dumpText". "dumpText" is dumped to the HTML element, with id: "forDump" (and hence the browser window) by the next line.

The third script, "testAJAXJSON.html" is:

Error: cannot call javascript function.

This script calls "testAJAXJSON.js".

To execute the scripts, enter the URL of "testAJAXJSON.html" in the browser's address bar. For instance, enter: "/var/www/testAJAXJSON.html" in the browser. The following line: "The name is: spruce blue; and the max height is: 40", or something similar, should be dumped.

Sometimes it is useful to have the PHP script return to the JavaScript code a few variables in addition to an array object. This can be accomplished by adding a known number of data chars to the start of the string returned by the PHP script. These are then read and removed before the string is sent to "JSON.parse" to be converted into the JavaScript object.

The following modifications of "jsonDemo.php" and "testAJAXJSON.js" demonstrate how this works. "jsonDemo.php" is modified as follows to return a 3 char numeric code:

Error: could not open javascript function.

The "printf" command prints the JSON encoded array after a three char string which includes the integer from the variable, "$num_code". For more information on the “printf” command see the links at the end of this section. Like the "echo" command, "printf" can be used to return a data string to the XMLHttpRequest object.

The "dumpScriptOutput(retText)" function of "testAJAXJSON.js" is modified to read this three char code and the array that follows.

function dumpScriptOutput(retText){
    var num_ret_str = retText[0]+retText[1]+retText[2];
    var num_ret = parseInt(num_ret_str);
    var array_str = retText.substring(3);
    array_ret = JSON.parse(array_str);
    var dumpText = "The number returned was:"+num_ret+"; and the name is: "
        +array_ret.name + "; and the max height is: " + array_ret.hmax;
    document.getElementById("forDump").innerHTML = dumpText; 
}
  • The line: "var num_ret_str = retText[0]+retText[1]+retText[2];" reads the first three chars from the string returned by the PHP script.
  • The next line: "var num_ret = parseInt(num_ret_str);" coverts this three char string into a number.
  • The line: "var array_str = retText.substring(3);" cuts the first three chars off of the returned string.
  • The next line, as before, converts the string into a JavaScript object.

The rest of the "dumpScriptOutput(retText)" function dump the results to screen.

If the names of the scripts have not been changed then, they can be run, as before, by accessing "testAJAXJSON.html".

V.3.3 Passing Variables from JavaScript to PHP for "GET" Requests

The syntax for passing variables from the JavaScript to the PHP for "GET" requests is as follows. The client-side JavaScript passes a string to the XMLHttpRequest object, for example:

var pass_v1 = "Apple";
var pass_v2 = "Malus";
var pass_v3 = 30;
var pass_str = "passVarsGETAJAX.php?var1=" + pass_v1 + "&var2=" + pass_v2 + "&var3=" + pass_v3;
req.open("GET",pass_str,true);

The string, "pass_str", contains both the name of PHP script to be called and the values of the variables passed to the script. The variables come in the passed string after the "?" symbol. Each of these variables has the format of "variable_name = variable_value". If multiple variables must be passed, then a "&" char is placed between them. The line "req.open("GET",pass_str,true)" configures the XMLHttpResponse object to open the PHP script and send it the variables as defined in the "pass_str".

The PHP script must be configured to read the variables passed by the XMLHttpResponse object. The following syntax reads the passed variables when the request method "GET" is used.

$v1 = $_GET["var1"];
$v2 = $_GET["var2"];
$v3 = $_GET["var3"];

The three scripts: "passVarsGETAJAX.php", "passVarsGETAJAX.js", and "passVarsGETAJAX.html", demonstrate how to call PHP from JavaScript and pass variables between the client-side and the server-side scripts. These script are discussed in section V.3.6.

V.3.4 Passing Variables from JavaScript to PHP for "POST" Requests

If the request method is "POST" then the syntax for passing the variables from the JavaScript to the PHP is slightly different. For the "open" function of the XMLHttpRequest object only the URL of the PHP script is passed:

req.open("POST","passVarsPOSTAJAX.php",true);

The "setRequestHeader" function is typically called to set the "Content-type" header of the "XMLHttpRequest" object to the value: "application/x-www-form-urlencoded":

req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Finally the "send" function of the "XMLHttpRequest" object is called; for the POST method a string of variables is passed to "send".

The following syntax is used to set up a "POST" request that passes three variables to the PHP script:

var pass_v1="Apple";
var pass_v2="Malus";
var pass_v3=30;
var pass_str="var1="+pass_v1+"&var2="+pass_v2+"&var3="+pass_v3;
req.open("POST","passVarsPOSTAJAX.php",true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(pass_str);

It is important that the three functions, "open", "setRequestHeader" and "send" are called in the order given.

V.3.5 Receiving Variables Passed by "POST" and "GET"

For "POST" request the variables passed to the PHP script can be read in the script with the following syntax:

$v1 = $_POST["var1"];
$v2 = $_POST["var2"];
$v3 = $_POST"var3"];

To retrieve variables passed by a "GET" request the same syntax is used except that "_POST" is replaced by "_GET".

The PHP function: "isset(str)" can be used with either "GET" or "POST" to test if the variable was set in the string passed from the XMLHttpRequest object. For example, for a "GET" request, the first variable could be retrieved, if set, as follows:

$v1="";
if(isset($_GET["var1"])){
    $v1=$_GET["var1"];
}

V.3.6 The Example Scripts

The three scripts, "passVarsGETAJAX.php", "passVarsGETAJAX.js", and "passVarsGETAJAX.html" are an example calling PHP from JavaScript and passing variables between the client-side and the server-side scripts using "GET".

The code for "passVarsGETAJAX.php" is as follows:

Error: could not open javascript function

The code for "passVarsGETAJAX.js" is as follows:

Error: could not open javascript function

The code for "passVarsGETAJAX.html" is as follows:

Error: could not open javascript function

The scripts can be run by sending the browser to the URL for "passVarsGETAJAX.html". It will print the following message:

The string returned by PHP is:
The variables set were: For var1, Apple; for var2, Malus; for var3, 30.

The three scripts, "passVarsPOSTAJAX.php", "passVarsPOSTAJAX.js", and "passVarsPOSTAJAX.html" are an example calling PHP from JavaScript and passing variables between the client-side and the server-side scripts using "POST".

These are "POST" versions of the scripts:

The code for "passVarsPOSTAJAX.php" is as follows:

Error: could not open javascript function

The code for "passVarsPOSTAJAX.js" is as follows:

Error: could not open javascript function

The code for "passVarsPOSTAJAX.html" is as follows:

Error: could not open javascript function

The scripts can be run by sending the browser to the URL for "passVarsPOSTAJAX.html". It will print the following message:

The string returned by PHP is:
The variables sent were: For var1, Apple; for var2, Malus; for var3, 30.