Click here to Skip to main content
15,880,469 members
Articles / Web Development / HTML

All Possible Data Exchange in AJAX

Rate me:
Please Sign up or sign in to vote.
4.75/5 (4 votes)
5 Oct 2010CPOL5 min read 29.9K   491   31  
Demo Application to Send Recieve Data with AJAX using QueryStrings, HttpHeaders, Post Data

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:

  1. open: Creates a connection
  2. send: Sends a request to the server

Data furnished by the server will be found in the attributes of the XMLHttpRequest object:

  1. responseXml for an XML file, or
  2. 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
  1. 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

  2. status: 200 is OK

    404 if the page is not found

  3. responseText: Holds loaded data as a string of characters.
  4. responseXml: Holds an XML loaded file, DOM's method allows to extract data.
  5. onreadystatechange: Property that takes a function as value that is invoked when the readystatechange event is dispatched.
Methods of XMLHttpRequest Class
  1. 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

  2. send("string"): string: POST data, null for a GET command
  3. abort() : Cancels the current HTTP request
  4. getAllResponseHeaders(): Retrieves the values of all the HTTP headers
  5. getResponseHeader(string): Retrieves the value of an HTTP header from the response body
    string: name of http header
  6. 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.

JavaScript
function AjaxRequest(ReadyHandler,URL,Method,Params,QueryString,HttpHeaders) {
    if (URL == null) { alert("Request URL is Empty"); }
    else {

        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        //An anonymous function is assigned to the event indicator. 
        xmlhttp.onreadystatechange = function() {
        
        //200 status means ok, otherwise some error code is returned, 404 for example
        //The 4 state means for the response is ready and sent by the server.  
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {   
                ResponseText = xmlhttp.responseText;   //get text data in the response
                ResponseXML = xmlhttp.responseXML; //get xml data in the response
                ResponseHeaderJSON = xmlhttp.getResponseHeader
		("CustomHeaderJSON");  // Extract Data in http header
                ResponseHeaders = xmlhttp.getAllResponseHeaders();   //Get a string 
				//containing all http headers returned by server
                
                // Make all the results available in the ReadyHandler via prototyping.
                ReadyHandler.prototype.ResponseText = ResponseText;
                ReadyHandler.prototype.ResponseHeaderJSON = ResponseHeaderJSON;
                ReadyHandler.prototype.ResponseXML = ResponseXML;
                ReadyHandler.prototype.ResponseHeaders = ResponseHeaders;
                // Execute function passed as ReadyHandelr
                ReadyHandler();
            }            
        }

        //If querystring is provided Attach it to the url
		if (QueryString != "") {
            var QueryStringData = "";
            for (QueryStringAttribute in QueryString) {
                QueryStringData = QueryStringAttribute + "=" + 
		QueryString[QueryStringAttribute] + "&" + QueryStringData;
            }
            QueryStringData = QueryStringData.substring(0, 
				QueryStringData.lastIndexOf('&'));
            URL = URL + "?" + escape(QueryStringData);      //Here is where the 
				//query string ia attached to the request url.
        }
        
        //POST or GET URL of the script to execute.true for asynchronous 
        //(false for synchronous).
        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]);  // Here the custom headers are added
            }            
        }
        
	//Post data provided then assemble it into single string to be posted to server
	if (Params != "") {
            var ParamsData = "";
            for (ParamName in Params) {
                ParamsData = ParamName + "=" + Params[ParamName] + "&" + ParamsData;
            }
            ParamsData = ParamsData.substring(0, ParamsData.lastIndexOf('&'));
        }
        
        xmlhttp.send(ParamsData); //Send the request with the post data
    }
} 

[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.

AJAXDemo.png

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.

JavaScript
FunctionCall = document.getElementById('FunctionCode').value;
eval(FunctionCall); 
Function Usage
JavaScript
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>.

JavaScript
function ProcessRequest() {
 
    // // Assign the content to the form 
    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:

JavaScript
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.

JavaScript
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:

C#
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 strings 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]:

Fiddler.png

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
function Nozel_Rosario(Imagination, Creativity, Computer_Programming) {
var Innovation = Imagination + Creativity * Computer_Programming ;
return Innovation;
}

Comments and Discussions

 
-- There are no messages in this forum --