Working with AJAX is a two-step process.
a. Send AJAX request to server
b. Receive and work with the data
a. Send AJAX request to server
AJAX request sent to server by using XMLHttpRequest
object, it is a JavaScript object designed by Microsoft and later adopted by
other browsers like Mozilla, chrome etc., By using XMLHttpRequest object, we
can retrieve any kind of data, not only XML (You can retrieve text, Json etc.,)
and in addition to http, it supports other protocols like ftp.
Create
XMLHttpRequest Object
As already said, this class originally
implemented in internet explorer as an ActiveX object called XMLHTTP, later
Mozilla, Safari and other browsers followed, implementing an XMLHttpRequest
class that supports the methods and properties of Microsoft's original ActiveX
object. So we need to create a cross-browser instance of XMLHttpRequest object,
that supports all browsers.
We can do this by using following
snippet.
if (window.XMLHttpRequest) { // Mozilla, Chrome, Safari, IE7+ ...... httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 6 and older try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ } } }
Ok fine, we came to know how to create
XMLHttpRequest object, next we need to decide what to do the response from the
server.
You can achieve this by using “onreadystatechange”
property of the XMLHttpRequest object.
httpRequest.onreadystatechange =
function(){
// process the server response
};
In side the function, you can write your
logic to handle the response data. One more thing, inside the function, you
need to check the state of the request (Wheteher request is completed
successfully, aborted etc.,)
You can check the state of the request
by using “readyState” property of XMLHttpRequest object.
State
|
Value
|
Description
|
UNSENT
|
0
|
open() has not been called yet.
|
OPENED
|
1
|
send() has not been called yet
|
HEADERS_RECEIVED
|
2
|
send() has been called, and headers
and status are available.
|
LOADING
|
3
|
Downloading; responseText holds
partial data.
|
DONE
|
4
|
The operation is complete.
|
if (httpRequest.readyState === 4) { if (httpRequest.status === 200) { //Request processed successfully } else { //There was a problem with the request } }
Make
request to the server
By using open() and send() methods of
XMLHttpRequest object we can make a request to the server.
Open()
Open() method is used to initialize a
request.
void open(
DOMString method,
DOMString url,
optional boolean async,
optional DOMString user,
optional DOMString password
);
Parameters
method:
specifies the request
type to use, like GET, POST, PUT, DELETE.
url:
The URL to send the
request to.
async:
It is optional
parameter, by default it set to true. If async is set to true, the execution of
the JavaScript function will continue while the response of the server has not
yet arrived. If async set to false the send()method does not return until the
response is received.
user
: Optional parameter,
specifies the user name for authentication purpose.
password
: Optional parameter,
specifies the password for authentication purpose.
Example
httpRequest.open('GET',
'http://localhost/getText');
send()
send the request to the server.
Overloaded forms of this method are
void send();
void send(ArrayBuffer data);
void send(ArrayBufferView data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
Is the request is asynchronous, then
this method returns as soon as the request sent. If the request is synchronous,
this method doesn’t return until the response has arrived.
Example
httpRequest.send();
Note
:
To send post data, you need to set the MIME type of
the request before calling send() like below.
httpRequest.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
b. Receive and work with the data
Once you send the request to the server,
you will get some response. You must provide a function to handle the response
from the server; we can do this with following snippet.
httpRequest.onreadystatechange = function(){ if (httpRequest.status === 200) { // Perfect response } else { // there was a problem with the request } };
I hope with this you understand the
basics of AJAX, it is time to write simple Application.
Step
1: Create a dynamic
webproject in eclipse and name it as “ajax_tutorial”.
Give project name as “ajax_tutorial” and
press next.
Select “Generate web.xml deployment
descriptor” and press Finish.
Total project structure looks like
below.
Step
2: Create new jsp file
“HelloWorld”.jsp like below.
HelloWorld.jsp
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("myDiv").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "hello_world.txt", true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"> <h2>Click the button to change text</h2> </div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
Step
3: Create new file “hello_world.txt”.
Right click on WebContent -> New
-> File
Give the file name as “hello_world.txt”
and press finish
Add content “Hello AJAX” to
hello_world.txt.
Run “HelloWorld.jsp”, it opens in
browser like below.
Click on the button “Change Content”, it
replace the content with content in “hello_world.txt” file.
Total project structure looks like
below.
No comments:
Post a Comment