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>
<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>
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'];
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";
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;
}
<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;
}
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.
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;>
<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;>
No comments:
Post a Comment