In order to make an HTTP request to the server using
JavaScript, an instance of a class that provides this functionality is
required. Such a class was originally introduced in Internet Explorer as an
ActiveX object and is called XMLHTTP. Then Mozilla, Safari and other browsers
also followed and started implementing an XMLHttpRequest class that supports the methods and properties supported by Microsoft's original ActiveX object.
Create a new XMLHttpRequest
Listing 1
<script language="javascript" type="text/javascript">
var XMLHttp=new xmlHttpRequest();
</script>
This is the object which handles all the server
communication.
In normal Web applications the users fill out form fields
and then click a Submit button. Then, the entire form is sent to the server
which passes it on to some script. When the script has finished its work, it
sends back a completely new page as the response. But during the time the
script or program on the server is processing and returning a new form, users
have to wait the entire time.
But in the case of Ajax, it puts the Javascript technology
and the XMLHttpRequest object between the user's Web form and the server. When
users fill out forms, the data, rather than being directly sent to the server,
is sent to a Javascript code. Thus, here Javascript code catches the form data
and sends a request to the server.
In order to create a cross-browser instance (object) of the
required class we need to write the code.
Listing 2
if (window.xmlHttpRequest)
{
// for Mozilla, Safari, etc.
XMLHttp = new xmlHttpRequest();
}
elseif(window.ActiveXObject)
{
// for Internet Explorer
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Microsoft's browser (Internet Explorer) uses the MSXML
parser for handling XML. MSXML has two different versions, so we need to write
code that handles both cases. Thus the code goes as shown below.
Listing 3
var XMLHttp = false;
try
{
XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (XMLHttp == false)
{
XMLHttp = new XMLHttpRequest();
}
The above code tries to create the object in one version of
MSXML. If XMLHttp still has its value as false, it tries to create the object
in the standard way.
Making a Request
First of all, a JavaScript method is required, which the web
page can call. Then we need to do the following.
·
Get the required data from the Web form
·
Build the URL for connecting
·
Open a connection to the server
·
Write a function that the server can run when it is done with its
work
·
Send the request
For this the required coding.
Listing 4
function getData() {
// Get the data in the name field from the web form
var name = document.getElementById("name").value;
// Proceed only if there is value for the field
if ((name == null) || (name == "")) return;
// Build the URL to connect to
var url = "/scripts/getAnswer.php?name=" + escape(name);
// Setup a function for the server to run when it's done
XMLHttp.onreadystatechange = showSuggestion;
// Open a connection to the server
XMLHttp.open("GET", url, true);
// Send the request
XMLHttp.send(null);
}
The first part of the code is simple JavaScript used to
catch the form data. Then the code sets a PHP script as the destination for
connecting to. First, the URL is specified and then the value of the name field
is appended to it. Then the onreadystatechange property has been used to inform
the HTTP request object about the JavaScript function to run after getting the
response from the server. This function handles further processing of the
response sent by the server. To make the actual request, a person needs to call
the open() and send() methods of the HTTP request class. The first parameter of
the open() function is the request method which can be GET,POST,HEAD or any
other method supported by the person's browser. The second parameter is the URL
of the page the person requests. The third parameter sets whether the request
is asynchronous or not. If TRUE, the execution of the JavaScript function will
continue while the response of the server has not yet arrived and if set to
false, it will wait for the server response which destroys the very meaning of Ajax i.e. asynchronous data retrieval. Finally, send() is called with a value of null.
Since the data to be sent to the server (the value of the name field) has
already been added in the request URL, it is not required to send anything in
the request. So this triggers the request and the server can do what it has
been asked to do.
Handling the Response
First, the function needs to check for the state of the
request. If the state has the value of 4, it means that the full server
response has already been received and it is OK to continue with the
processing.
Listing 5
if (XMLHttp.readyState == 4)
{
// the response has been fully received
}
else
{
// still not ready with the response
}
The full list of the "readystate" values is shown
below:
·
0: The request is uninitialized (before open() is called).
·
1: The request is set up, but has not been sent yet (before
send() is called).
·
2: The request was sent and is being processed at present.
·
3: The request is being processed; often some partial data is
available, but the server has not finished with the response.
·
4: The response is complete and can be used.
The next thing to check is the status code of the HTTP
server response. Here it is required to check only the "200" i.e. "OK"
response.
Listing 6
if (XMLHttp .status == 200)
{
// you can move on
}
else
{
// there was a problem with the request,
// (example-the response may be a 404 (i.e. Not Found)
}
Now, after checking the state of the request and the HTTP
status code of the response, a person needs to decide what to do with the
server response. There are two options to access that data:
·
XMLHttp.responseText – will return the server response as a
string of text
·
XMLHttp.responseXML – will return the response as an XMLDocument
object
The code is as shown:
Listing 7
function showSuggestion()
{
if (XMLHttp.readyState == 4)
{
if (XMLHttp.status == 200)
{
var response = XMLHttp.responseText;
document.getElementById("Suggestion").value = response;
}
else
{
alert('There was a problem with the request.');
}
}
}
It waits for the server to call it with the proper ready
state and status. Then it uses the data returned by the server (in this case, the
suggestions for the data entered by the user) to set the value of another form
field. The result is that the Suggestion field suddenly appears with the
suggestions for the name field but without requiring the user to click a submit
button.
Finally, here goes the HTML form.
In this form there is a text input for the user to enter
data and another placeholder to show the suggestions.
Listing 8
<form>
<p>Name: <input type="text" name="name" id="name" size="25"
onChange="getData();" /></p>
<p>Suggestion: <span id="Suggestion"></span></p>
</form>
Here, span is used as a placeholder for data retrieved from
the web server. When a user writes in a new value for name field, the getData()
method is called up and the user is able to view the suggestions without having
to click a button. This is what makes Ajax grab the attention of the
developers.