GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Monday, May 9, 2011

JS -- AJAX

Introduction

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()"/>

<script>

function sending(){

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

}

</script>
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()"/>

<script>

function receive(){

  var msg = document.getElementById('msg');
  var ajax = new XMLHttpRequest();
  ajax.open('GET', 'hello.php', false);
  ajax.send();
  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()"/>

<script>

function load(){

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

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

  msg.innerHTML = ajax.responseText;

}

</script;>


Share/Bookmark

No comments:

Post a Comment