Ajax and PHP

PHP and Ajax are combined by webmasters to make Web applications as complete as desktop applications.

Ajax allows you to create an interface that runs on a browser with JavaScript, now extremely fast on the latest versions of browsers.

PHP runs on the server and it consults a database and automatically update it with data entered through the interface and it executes processing requested by the user, requiring data stored on the server.

How to make the interaction between the interface in Ajax and PHP scripts on the server?

The Ajax tutorial provides the basics, including the demonstration of the POST command to send data to a PHP script that writes them into a file on the server.

Interaction between Ajax and PHP using GET

There was no difference with the Ajax code to load a file, except that the filename is a script with the PHP extension rather than a simple text file.

And in this case, the variable responseText will not be assigned with the file, but with what the PHP script displays.

For example, if the PHP script holds this command:

   echo "Hello!";

responseText will hold: Hello!

The JavaScript code will be:

function createInstance()
  var req = null;
  if(window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  else if (window.ActiveXObject) {
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
       try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            alert("XHR not created");
    return req;

function submitForm()
   var req = createInstance();
   req.onreadystatechange = function()
      if(req.readyState == 4)
         if(req.status == 200)
            alert("Error: returned status code " + req.status + " " + req.statusText);
   req.open("GET", "ajax-get.php", true); 

Demo of the Ajax GET Command for a PHP Script

This page use Ajax to runs the ajax-get.php script.

What the PHP script display is then assigned to responseText, that will be displayed below.
No difference with the use of GET to load a text file, only the name of the file differs!

The PHP script displays will be inserted here

Using POST and PHP

The Ajax code is very simple.

A string is built from the data:

var data = "var1=" + value1 +  "&var2=" + value2;

And it is sent to the server using the XMLHttpRequest object:

xhr.open("POST", "script.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  

Data taken from a form in the HTML interface, are sent to the server by the send() method of the XMLHttpRequest object, and a PHP program, named script.php for example, receives them as parameters and performs some processing for which it is programmed.

The PHP code might look like this:

$myarray = &$_POST ; 
... processing...

Values value1 and value2 sent by the JavaScript interface are assigned to the PHP variables $var1 and $var2.

We can go further by seeing how that is stored into a database ...

Using a PHP script with a parameter sent by a Web page. In the example, the parameter is a URL and the script checkes whether this URL is a valid link.

The JavaScript code that launches the script and provide it with the parameter:

function storing(data)
    var element = document.getElementById('storage');
element.innerHTML = data; } function submitForm(element) { var req = createInstance(); var url = document.ajax.url.value; var data = "url=" + url; req.onreadystatechange = function() { if(req.readyState == 4) { if(req.status == 200) { storing(req.responseText); } else { alert("Error: returned status code " + req.status + " " + req.statusText); } } }; req.open("POST", "pingurl.php", true); req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.send(data);

Ping a Web page by Ajax and PHP, using the POST method

Demo using Ajax to run on the server the pingurl.php script with for parameter the URL of a Web page.
The script checks that the URL is a valid link.

The POST command allows to pass parameters to the PHP script.

The answer of the script will be assigned to responseText, which will be shown below.

The answer will come here

Interacting with an SQL database

One can imagine a table named mytable, with columns named var1 and var2.


PHP has functions for reading and writing in a SQL table, and this in fact has no dependence with Ajax.

$base = mysql_connect($HOST, $USER, $PWD);  
mysql_select_db($name, $base); 
$query = "INSERT INTO mytable(var1, var2) VALUES ('$var1', '$var2'')"; 
mysql_query($query, $base);

The data from an HTML form are transferred to the PHP script that inserts them into an SQL database in a few lines ...


Ajax provides to PHP, a scripting language operating mainly on servers, what is lacks: a graphical interface allowing the user to interact with an online application, working with instant reactivity.


© 2009-2012 Xul.fr