Introduction
This is a demo application to send receive data with AJAX using QueryStrings, HttpHeaders, Post Data.
AJAX
You can always get all the description on the internet about AJAX.
Short Description of AJAX
Ajax is only a name given to a set of tools that were previously existing.
The main part is XMLHttpRequest
, a server-side object usable in JavaScript, that was implemented in Internet Explorer since the 4.0 version.
To get data on the server, XMLHttpRequest
provides two methods:
open
: Creates a connection send
: Sends a request to the server
Data furnished by the server will be found in the attributes of the XMLHttpRequest
object:
responseXml
for an XML file, or responseText
for a plain text
Take note that a new XMLHttpRequest
object has to be created for each new data request.
We have to wait for the data to be available to process it, and in this purpose, the state of availability of data is given by the readyState
attribute of XMLHttpRequest
.
Attributes of XMLHttpRequest Class
- readyState: The code successively changes value from 0 to 4
0: Not initialized
1: Connection established
2: Request received
3: Answer in process
4: Finished
- status: 200 is OK
404 if the page is not found
- responseText: Holds loaded data as a
string
of characters. - responseXml: Holds an XML loaded file, DOM's method allows to extract data.
- onreadystatechange: Property that takes a function as value that is invoked when the
readystatechange
event is dispatched.
Methods of XMLHttpRequest Class
- open(mode, url,boolean) : mode: type of request,
GET
or POST
url: the location of the file, with a path
boolean: true
(asynchronous) / false
(synchronous)
optionally, a login and a password may be added to arguments
- send("string"):
string
: POST
data, null
for a GET
command - abort() : Cancels the current HTTP request
- getAllResponseHeaders(): Retrieves the values of all the HTTP headers
- getResponseHeader(string): Retrieves the value of an HTTP header from the response body
string: name of http header - setRequestHeader(name,value): Adds a new http header in the request
name: name/identifier of the header
value: value of the header
Using the Code
Here is a simple function 'AjaxRequest
' which is implemented to perform the AJAX requests.
function AjaxRequest(ReadyHandler,URL,Method,Params,QueryString,HttpHeaders) {
if (URL == null) { alert("Request URL is Empty"); }
else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
ResponseText = xmlhttp.responseText;
ResponseXML = xmlhttp.responseXML;
ResponseHeaderJSON = xmlhttp.getResponseHeader
("CustomHeaderJSON");
ResponseHeaders = xmlhttp.getAllResponseHeaders();
ReadyHandler.prototype.ResponseText = ResponseText;
ReadyHandler.prototype.ResponseHeaderJSON = ResponseHeaderJSON;
ReadyHandler.prototype.ResponseXML = ResponseXML;
ReadyHandler.prototype.ResponseHeaders = ResponseHeaders;
ReadyHandler();
}
}
if (QueryString != "") {
var QueryStringData = "";
for (QueryStringAttribute in QueryString) {
QueryStringData = QueryStringAttribute + "=" +
QueryString[QueryStringAttribute] + "&" + QueryStringData;
}
QueryStringData = QueryStringData.substring(0,
QueryStringData.lastIndexOf('&'));
URL = URL + "?" + escape(QueryStringData);
}
xmlhttp.open(Method, URL, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if (HttpHeaders != "") {
var HttpHeadersData = "";
for (HttpHeaderName in HttpHeaders) {
xmlhttp.setRequestHeader(HttpHeaderName,
HttpHeaders[HttpHeaderName]);
}
}
if (Params != "") {
var ParamsData = "";
for (ParamName in Params) {
ParamsData = ParamName + "=" + Params[ParamName] + "&" + ParamsData;
}
ParamsData = ParamsData.substring(0, ParamsData.lastIndexOf('&'));
}
xmlhttp.send(ParamsData);
}
}
[You can find the complete implementation with sufficient comments in the source code.]
It can give a more clear idea of using AJAX in your applications.
In the demo application, you can test the 'AjaxRequest
' function by changing the parameters that are passed to it.
Actually all the code that is typed in the text box is executed as JavaScript code on click of 'Execute' button.This is done using the eval()
function.
FunctionCall = document.getElementById('FunctionCode').value;
eval(FunctionCall);
Function Usage
function AjaxRequest(ReadyHandler,URL,Method,Params,QueryString,HttpHeaders)
Description
-> ReadyHandler: Function to be called after successful completion of the AJAX request
Note: On successful completion of the request, the result of the request will be available in the function passed as ReadyHandler.
The result of request will be in 4 variables, namely:
ResponseText
: Text response from server ResponseHeaderJSON
: Custom HTTP Header String value
This header string may contain a single string
value or a you can also use a JSON format for multiple values which then can be parsed in ReadyHandler
(as shown in the example).
ResponseHeaders
: String
containing all Response HTTP Headers ResponseXML
: XML response from server (XML object available only when the Response contains a proper XML)
-> URL
: This parameter takes the URL to which the request is to be sent
-> Method
: Method of request "GET
"/"POST
"
-> Params
: POST
data to be sent to server. Expects a JSON formatted name value pairs
-> QueryString
: Data to be sent to the server as QueryString
. Expects a JSON formatted name value pairs
-> HttpHeaders
: Data to be sent as HTTP Headers. Expects JSON formatted name value pairs
Note: While sending the data in headers, you have to take care only ASCII characters where charCode ranging from 32 to 126 are sent or you may get unexpected results. See RFC documentation for HTTP.
The ReadyHandler
can contain the code which will dynamically change the contents of the webpage based on the response data.
For example, in the demo application, I have used 'ProcessRequest()
' as the Ready handler which sets the response in the respective <Div>
.
function ProcessRequest() {
document.getElementById('ResponseTextDiv').innerHTML = ResponseText;
document.getElementById('ResponseXMLDiv').innerHTML = ResponseHeaders;
eval("var CustomHeaders = { " + ResponseHeaderJSON + "};");
var header;
var allHeaders = "<br/>";
if (CustomHeaders != "") {
for (header in CustomHeaders) {
allHeaders = allHeaders + CustomHeaders[header] + "<br/>"
}
}
document.getElementById('ResponseHeadersDiv').innerHTML = allHeaders;
}
Example:
AjaxRequest(ProcessRequest, 'Handler.ashx','POST',
{ Param1: 'Param1Value', Param2: 'Param2Value', Param3: 'Param3Value' },
{ Query1: 'Q1', Query2: 'Q2', Query3: 'Q3' },
{ Header1: 'H1', Header2: 'H2', Header3: 'H3' }
);
For handling the client request, I have implemented a simple Generic Handler (.ashx).
You can access all the data (query string + Post Data + HTTP Headers) that is sent by the client browser in AJAX request.
In the Generic handler, the data is accessible via the context.Request
object.
Though you can access all the data together in context.Request.Params[]
, you can access the data separately as follows:
- Query String:
context.Request.QueryString[[index/string]]
- Http Headers:
context.Request.Headers[[index/string]]
In the example application, what I have done is just echo back the data which is received in the request along with a custom HTTP header added.
foreach(string Param in context.Request.Params)
{
ParamsData ="<br/>" + Param + " : " +
context.Request.Params[Param].ToString() + ParamsData;
}
context.Response.Write(ParamsData);
The above lines capture the data in the request and send it back in the response.
For adding an extra custom HTTP header in response:
context.Response.AddHeader("CustomHeaderJSON", CustomHeaderJSON);
As you see, the context.Response
object is used to assemble the response which is to be sent back to the browser.
Different methods of context.Response can be used to do this.
'CustomHeaderJSON' can contain a string
, but I have created a JSON format string
for supporting multiple values.The values are then parsed at client side using JavaScript.
I have just used string
concatenate for creating it, but you can also use different JSON parsers/Encoders available at http://www.json.org/.
You can also use JSON string
s to exchange data through AJAX. It is sometimes better to use JSON than XML. Using JSON results in less bytes transferred than XML.
Points of Interest
This is a basic implementation of AJAX and the function can be tuned and modified according to needs and reconfigurability.
Here is how the request and response looks like [HTTP request in Fiddler]: