Send Data With Ajax and PHP

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 9

Retrieve data in Ajax and PHP in plain

text
Description
This tutorial explains how to use Ajax in order to retrieve whenever you want the data
sent by your PHP script in plain text.

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 need to create a file call form.html. This file will contains only one button
that allows retrieving the data sent by the PHP script.
form.html
<html><head>
<script language="javascript" src="Ajax.js"></script>
</head><body>
<form action="">
<input type="button" onclick="retrieveData()" value="ajax"/>
</form>
</body></html>
As you can see, when we click on the ajax button, the function retrieveData() is
called. This function is defined in the file Ajax_txt.js.

JavaScript script
We will now create a new file called Ajax_txt.js. This file will contains the function that
allows creating an instance that allows sending http requests to the server and another
function that allows retrieving the response from the server.

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 : represents the connection state.


o 0 : connection not initiated.
o 1 : connection established.
o 2 : request received.
o 3 : response pending.
o 4 : done.
status : represents the state of the page sent by the server.
o 200 : OK.
o 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.


o mode: request type, GET or POST
o 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.
o boolean: true (asynchronous) / false (synchronous).
send("string"): Send data to the server. Null for GET command.

For creating XMLHttpRequest object instance, 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
}
};

Retrieve the data


Now we will use the XMLHttpRequest object in order to retrieve the data sent by the
server. To do that, add the following function:
Ajax.js
function retrieveData(){
var req = createInstance();
var clientData = null;
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", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
/* We send the data */
req.send(clientData);
}
As you can see, we check if the connection is done and if the status of the data sent by the
server is ok.
In this tutorial, I explain how to retrieve the response from the server in plain text but we
can also use Ajax queries to retrieve the response inside an XML file.

PHP script
Now we will write the PHP script on the server side. This script is very simple. Create a
file call server.php and add the following code inside:
server.php

<?php
echo "data";
?>

Tests
This tutorial comes to his end. You can test your application by clicking on ajax
button. The message: data should be displayed.

Send data with ajax and PHP


Category: Javascript.
Posted by Koener Herv 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.


o 0: connection not initiated.
o 1: connection established.
o 2: request received.
o 3: response pending.
o 4: done.
status : represents the state of the page sent by the server.
o 200: OK.
o 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.


o mode: request type, GET or POST.
o 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.
o 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.

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.

Helpful utility functions


bool class_exists ( string class_name)
bool get_class ( object object)
array get_declared_classes ( void )
There are three particular OOP-related functions that will make your life easier, and these
are class_exists(), get_class(), and get_declared_classes(). In order, class_exists() returns
true if the specified class has been declared, get_class() returns the class name of the
object you pass to it, and get_declared_classes() returns an array of all classes that you
can currently create an object of.
Here are some examples:
<?php
if ($foo == $bar) {
$sam = new employee;
} else {
$sam = new dog;
}

?>

print "Sam is a " . get_class($sam) . "\n";


print "Class animal exists: " . class_exists("animal") . "\n\n\n\n";
print "All declared classes are: " . get_declared_classes() . "\n";

As you can see, the most common use for get_class() is when one object can be of
several possible types, as in the code above. C++ users will be familiar with the concept
of Runtime Type Information (RTTI), and this is pretty much the same thing.

You might also like