Publishing System Settings Logout Login Register
AJAX: Asynchronous Javascript and XML (Using PHP to send data)
TutorialCommentsThe AuthorReport Tutorial
Tutorial Avatar
Rating
Add to Favorites
Posted on July 23rd, 2005
13351 views
JavaScript
AJAX: Asynchronous JavaScripting and XML
AJAX is the future; Ajax allows you to send and receive data to / from the server without refreshing.
This is done by means of Javascript and optionally XML.
This tutorial will teach you the basics of sending / receiving data from your server.
Note that AJAX is NOT a language! This is more a Javascript than PHP tutorial!

Table of Content:
1. Introduction to AJAX
2. The Basics

1. Introduction to AJAX

Ajax isn�t a technology. It�s really several technologies, each flourishing in its own right,
coming together in powerful new ways. Ajax incorporates:

- standards-based presentation using XHTML and CSS;
- dynamic display and interaction using the Document Object Model;
- data interchange and manipulation using XML and XSLT;
- asynchronous data retrieval using XMLHttpRequest;
- and JavaScript binding everything together.


The classic web application model works like this: Most user actions in the interface trigger
an HTTP request back to a web server. The server does some processing � retrieving data,
crunching numbers, talking to various legacy systems � and then returns an HTML page to the client.
It�s a model adapted from the Web�s original use as a hypertext medium, but as fans of The Elements
of User Experience know, what makes the Web good for hypertext doesn�t necessarily make it good for
software applications.

(source)

The XML side of AJAX is optional.

2. The Basics
This part of the tutorial will teach you the very basics of sending and receiving data
using Javascript. The XML side will not be used in this tutorial.

We're going to need the following HTML for this tutorial.
Put it in ajax.html and upload to your server.

<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />
<script src=\"main.js\"></script>
</head>

<body>
<form name=\"form_select\">
<select name=\"select_select\" onChange=\"info1()\">
<option value=\"\" selected=\"selected\">Select ID#</option>
<option value=\"1\">ID# 1</option>
<option value=\"2\">ID#1 2</option>
</select>
</form>
<div id=\"my_div\">
Please select an ID# in the select field!
</div>
</body>
</html>


Now, we're going to have to create the XMLHttpRequest object.
This is done like this for IE:

x = new ActiveXObject(\"Microsoft.XMLHTTP\");


And for other browsers:

x = new XMLHttpRequest();


The following script (as commonly seen in other AJAX javascripts) is used to detect which browser the client is using.
If the browser is Internet Explorer we make the object with ActiveX.
(note that ActiveX must be enabled for it to work in IE)

function makeObject(){
var x;
var browser = navigator.appName;
if(browser == \"Microsoft Internet Explorer\"){
x = new ActiveXObject(\"Microsoft.XMLHTTP\");
}else{
x = new XMLHttpRequest();
}
return x;
}

Now let's get on to the next part.

var request = makeObject();

The javascript variable request now holds our request object.
Without this, there's no need to continue reading because it won't work ;)

Below you will find a snippet of code. I will explain it piece by piece later on.

function info1(){
request.open('get', 'test.php?id=' + document.form_select.select_select.selectedIndex);

request.onreadystatechange = parseInfo;

request.send('');
}


This piece of code sends the data from our select form field 'id' to test.php using GET method.
The data from the select is in $_GET['id'].

request.open('get', 'test.php?id='
+ document.form_select.select_select.selectedIndex);

The function open() is used to open a connection.
Parameters are 'method' and 'url'. For this tutorial we use GET.
We send it to 'test.php?id=' and add the index from our SELECT form field.

request.onreadystatechange = aprseInfo;

This tells the script to call parseInfo() when the ready state is changed.

request.send('');

This sends whatever we need to send. Unless you're using POST as method, the parameter is to remain empty.

function parseInfo(){
if(request.readyState == 1){
document.getElementById('my_div').innerHTML = 'Loading...';
}
if(request.readyState == 4){

var answer = request.responseText;

document.getElementById('my_div').innerHTML = answer;
}
}


This piece of code is initiated when the data is sent from the function info1().
It checks for status; 1 means loading, 2 means loaded and 4 means finished.
While it's loading, we add the text 'loading...' to our div with the id 'my_div'.
After it's done loading, we get the response from the server.

if(request.readyState == 1){
document.getElementById('my_div').innerHTML = 'Loading...';
}

While we are still waiting for a response, we replace whatever's in the div # 'my_div' with
the text 'Loading...'.

if(request.readyState == 4){

var answer = request.responseText;

document.getElementById('my_div').innerHTML = answer;
}

request.responseText holds the response we got from the server.
We assign it to a variable and replace the content of 'my_div' when it's done loading.

Save all of the code from here into main.js on your server

Next up is the PHP back-end for this.
This is very simple, therefore it needs little explaination.

<?php
if( $_GET['id'] == 1 )
{
echo 'Username: Bob<br />Posts: 12';
}
else
{
echo 'Username: Steve<br /> Posts: 33';
}
?>


As the javascript in main.js sends data to 'test.php?id=', the ID we need is in $_GET['id'].
We simply echo whatever we want to appear on the screen. In your web applications, youcan use
MySQL connection / fetches if you like, maybe other things. Just make sure always to echo it out.

Save this PHP into test.php. Have fun with your nice little script :)

Live Example: http://www.pixel2life.com/twodded/staff/cliff/ajax/
Premium Publisher
Dig this tutorial?
Thank the author by sending him a few P2L credits!

Send
Ruben K

i am totally awesome
View Full Profile Add as Friend Send PM
Pixel2Life Home Advanced Search Search Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Pixel2life Homepage Submit a Tutorial Publish a Tutorial Join our Forums P2L Marketplace Advertise on P2L P2L Website Hosting Help and FAQ Topsites Link Exchange P2L RSS Feeds P2L Sitemap Contact Us Privacy Statement Legal P2L Facebook Fanpage Follow us on Twitter P2L Studios Portal P2L Website Hosting Back to Top