Monday, May 9, 2011



AJAX is a mechenisme for communicating with server through background. It enables your client web site to load and sending data from and to server respectively without reloading the page.

Sending Data To Server

Here's a simple example on how to use ajax.

Program Code: Client Side

<input type="text" id="name"/>
<input type="button" value="Send" onclick="sending()"/>


function sending(){

  var name = document.getElementById('name').value;
  var ajax = new XMLHttpRequest();"GET", "hello.php?name="+name, false);


It's not so complicated. The fisrt, you have the data. The second, you declare an object instance of ajax throught XMLHttpRequest. Then you send your data through ajax. Finish.
And on the server side, you need to write the code to handle it. Here's a code on PHP.

Program Code: hello.php

$name = $_GET['name'];
From the above code, you see that you handling the data as it comes from common request.

Receiving Data From Server

After showing you on how to send data to server, now we are ready to handling the response data from server. Here's a code.

Program Code: hello.php

echo "Hello From Server";
The above code is the server code for sending to client. Below is the client code.

Program Code:

<h1>Message From Server:</h1>
<h2 id="msg"></h2>
<input type="button" value="Send" onclick="receive()"/>


function receive(){

  var msg = document.getElementById('msg');
  var ajax = new XMLHttpRequest();'GET', 'hello.php', false);
  msg.innerHTML = ajax.responseText;


In the above code, we will get the message from server and then display it.

Special Case: Ajax For Local File

If you have no web server, don't be hopeless. Because you can try simple ajax processing using local file. Here's a step: create a directory on D:\, and name it ajax. Then open an text editor, write this text below, and save it as hello.txt

Text File: hello.txt

Hello. This comes from local file.
Then make second file, write this code and save it as lola.html

Program Code: lola.html

<h1>What the message from a local file?</h1>
<h2 id="msg"></h2>
<input type="button" value="Load..." onclick="load()"/>


function load(){

  var msg = document.getElementById('msg');

  var ajax = new XMLHttpRequest();'GET', 'hello.txt', false);

  msg.innerHTML = ajax.responseText;




No comments:

Post a Comment