Galactic Civilizations 3
Send data with ajax and PHP

Send data with ajax and PHP

Category: Javascript.
Posted by on the 01/08/2013.
Last update on the 01/08/2013.

<<Previous tutorial 

Description

This tutorial explains how to use ajax in order to send GET or POST data to a PHP script.

Introduction

This tutorial can be realized with a simple text editor like « Notepad ». This tutorial requires some basic knowledge in html, JavaScript and PHP.

HTML form

First of all, we will create a file with the name form.html. This file will contains only one button that allows sending data to the PHP script.

form.html

<html><head>
<script
language="javascript" src="Ajax.js"></script>
</head><body>
<form
name="myForm" action="">
   <input
type="text" name="data" value=" "/>
   <input
type="button" onclick="sendData()" value="send"/>
</form>
</body></html>

We can see that, when we click on the « send » button, the function « sendData() » is called. This function will be defined in the file Ajax_send.js.

JavaScript

We will now create the file called Ajax_send.js. This file will contain the function that create the instance that allows sending a http request to the server and a function that send the data and retrieve the server response.

The XMLHttpRequest object

The first function allows to instantiate the XMLHttpRequest object. This one allows interacting with the server through its methods and attributes.

List of attributes:

  • readyState : represent the state of the connection.
    • 0: connection not initiated.
    • 1: connection established.
    • 2: request received.
    • 3: response pending.
    • 4: done.
  • status : represents the state of the page sent by the server.
    • 200: OK.
    • 404: page not found.
  • responseText : contains the data in plain text.
  • responseXml : contains the data in xml.
  • onreadystatechange : this property is activated when the current state is updated. We assign a function to this property.

List of methods:

  • open(mode, url, boolean): Open a new connection.
    • mode: request type, GET or POST.
    • url: PHP script url. For the GET command, data that need to be sent to server must be placed in the query string of the url.
    • boolean: true (asynchronous) / false (synchronous).
  • send("string"): Send data to the server. Null for GET command.

To create the instance of the XMLHttpRequest object, you need to add the following function:

Ajax.js

function createInstance(){
if(window.XMLHttpRequest){
   /* Firefox, Opera, Google Chrome */
   return new XMLHttpRequest();
}else if(window.ActiveXObject){
   /* Internet Explorer */
   var names = [
      "Msxml2.XMLHTTP.6.0",
      "Msxml2.XMLHTTP.3.0",
      "Msxml2.XMLHTTP",
      "Microsoft.XMLHTTP"
   ];
   for(var i in names){
      /* We test the different versions */
      try{ return new ActiveXObject(names[i]); }
      catch(e){}
   }
   alert("Not supported");
   return null; // Not supported
}
};

Send data with GET

We will now use the XMLHttpRequest object in order to send the data in GET and retrieve the response sent by the server. To do that, add the following function:

Ajax.js

function sendData(){
   var req = createInstance();
   /* We retrieve the form data */
   var userData =document.myForm.data.value;
   req.onreadystatechange = function(){
      /* If the state = done */
      if(req.readyState == 4){
        /* If the status = OK */
        if(req.status == 200){
         /* We display the response */
         alert(req.responseText);
        }else{
         alert("Error: returned status code " + req.status + " " + req.statusText);
        }
      }
   }
  
   req.open("GET", "server.php?data="+userData, true);
   req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   /* We set to null because we use the GET command */
   req.send(null);
}

As you can see, we check if the connection is closed and if the status of the data sent by the server is ok.

In this tutorial, I explain how to use ajax in order to send GET or POST data to a PHP script but we can also use ajax queries to retrieve the response inside an XML file or to retrieve the response as plain text.

PHP script

We will now write the PHP server-side script. You will see that this script is very simple. The PHP file that we will create is named: server.php.

server.php

<?php
echo "data recieved: ".$_GET["data"];
?>

Tests

We can test the script by clicking on the « send » button.

Ajax sent data with GET command

Send data with POST

Now, we will modify the file Ajax.js and more precisely the function sendData in order to send data with the POST command. To do that, modify the script as follow:

Ajax.js

...
/* We tell to the server that the data should be stored in the variable « data »*/
userData = "data="+userData ;
req.open("POST", "server.php", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
/* For the POST command the data are put in the body of the http request
and therefore they are sent as argument into the send function */

req.send(userData);
...

If we want to use more than one POST variable, we need to separate the variables name by the character: « & ». Here is an example: data = "d1="+d1+"&d2="+d2 ;

PHP script

Now we will update the PHP server-side script. There are only few modifications to be done:

server.php

<?php
echo "data recieved: ".$_POST["data"];
?>

Tests

We can test the script by clicking on the « send » button.

Ajax sent data with POST command

You like this tutorial ?
Like this website in order to promote it on facebook !

<<Previous tutorial 

You like this tutorial ? Share it with your friends !
Partager sur Facebook Partager sur Twitter Partager sur Myspace Partager sur Stumbleupon Soumettre sur Reddit Partager sur Digg Ajouter à vos favoris Technorati Ajouter à vos favoris Live Ajouter à vos favoris Google Ajouter sur vos favoris Yahoo