With traditional HTML and JavaScript, to get some data from the server side, it was necessary to make a form submission. With each submission the entire form was being reloaded. So it was loading an entirely new page and that was making performance slow.
By 2003, all the major browsers adopted the XMLHttpRequest (XHR) object, that allowed browsers to communicate with the server directly without a page reload.
The JavaScript object “XMLHttpRequest” is actually part of AJAX technology. Using the XMLHttpRequest API, JavaScript can directly interact with the server. The user can make a request to the server with a HTTP Get Response from the server and modify the required portion only (without a form submission/reload). But, various browsers implement it differently. For example Internet Explorer uses an ActiveXObject whereas other modern browsers use the built-in “XMLHttpRequest” JavaScript object.
So it's an overhead for developers to make implementation of XMLHttpRequest universal. To create an object that can call Server-side functionality directly we need to consider other browsers like:
- function CreateAsyncObject()
- {
- var ObjXmlHttp;
- try
- {
- ObjXmlHttp = new XMLHttpRequest();
- }
- catch(Exception OuterEx)
- {
- try
- {
- ObjXmlHttp = ActiveXObject(“Msxml2.XMLHTTP”);
- }
- catch(Exception Ex)
- {
- try
- {
- ObjXmlHttp = ActiveXObject(“Microsoft.XMLHTTP”);
- }
- catch(Exception ExInner)
- {
- alert(“Your browser doesn't support XMLHttpRequest.”);
- }
- }
- }
- }
Then we need to open this object with the required parameters and send it to the server like:
- ObjXmlHttp.open(“<GET/POST>”, “<Server side url>”, <true/false>);
The last parameter indicates whether the request is to be handled asynchronously.
Properties of XMLHttpRequest
- ReadyState: It has a value from 0 to 4.
- The XMLHttpRequest object is created, but open() has not been called.
- open () is called, but not send().
- send() has been called
- The browser has established a connection with the server but the server hasn't processed the response.
- The response data has been completely received from the server.
- Onreadystatechange: This is an event handler for the change in readyState
- responseText: Server response as a string
- responseXML: Response as XML.
- status: status of the HTTP request(200, 404 and so on)
- statusText: status as a message (“OK”, “Not found” and so on)
A complete request using XMLHttpRequest will be as follows:
- <input type= “text” onkeyup = “GetName()”>
- <div id= “divResult”></div>
-
- function GetName()
- {
- var ObjXmlHttp;
- try
- {
- ObjXmlHttp = new XMLHttpRequest();
- }
- catch(Exception OuterEx)
- {
- try
- {
- ObjXmlHttp = ActiveXObject(“Msxml2.XMLHTTP”);
- }
- catch(Exception Ex)
- {
- try
- {
- ObjXmlHttp = ActiveXObject(“Microsoft.XMLHTTP”);
- }
- catch(Exception ExInner)
- {
- alert(“Your browser doesn't support XMLHttpRequest.”);
- }
- }
- }
- ObjXmlHttp.open(“GET”, “GetName.aspx”, true);
- ObjXmlHttp.onreadystatechange(function(){
- if(readyState == 4)
- {
- divResult.innerHTML = ObjXmlHttp.responseText;
- }
- });
- }
jQuery-Ajax
jQuery provides Ajax support that removes all the overhead of creating objects (considering various browsers), handling a “readystatechange” event, checking readyState and so on. By some full-featured method like $.ajax() and some convenience methods like $.get(), $.post() and so on.
There are many $.ajax() Options available. Some of the most common properties are:
Option |
Description |
Default value |
async |
If the request should be served asynchronously |
(true) |
url |
URL to request. This is the only required value to make an Ajax call |
|
contentType |
Type of content query is ed to the server |
application/x-www-form-urlencoded;charset=UTF-8 |
data |
Data query is ed to the server |
|
dataType |
Type of data jQuery is expecting from server |
MIME type of response |
success |
Success callback |
|
error |
Error callback |
|
complete |
Code to execute irrespective of success/failure |
|
crossDomain |
It indicates if request is to/from cross-domain |
(false) |
NOTE: If you are not sure about ContentType and dataType, just don't mention them in the configuration of a jQuery Ajax call, It'll take default values that will satisfy most of the types.
- $.ajax({
- type: "POST",
- url:"http://localhost/WebServiceForBlog/MyService.asmx/SumOfNums",
- data: "First=" + FirstNum + "&Second=" + SecondNum,
- contentType: "application/x-www-form-urlencoded;charset=UTF-8"
- dataType: "text",
- crossDomain: true,
- success: function (data) {
- $('#divSum1').html(data);
- }
- error: function(data)
- {alert("Error");}
- });
Let's discuss one of the most commonly used callback functions.
error
- function(jqXHR, textStatus, errorThrown).
- jqXHR: A string describing the type of error that has occurred and an exception object (if occurred).
- TextStatus: request status like null, "timeout", "error", "abort", and "parsererror".
- ErrorThrown: Textual portion of the HTTP status, such as "Not Found".
Success
- function(data, textStatus, jqXHR).
- data: data returned from server.
- textStatus: string decribing the status.
- JqXHR: success setting.
These jQuery methods use the XMLHttpRequest API internally for calling server-side functionalities directly.
By default, Ajax doesn't support cross-domain calls since it violates “Same origin policy”. JSONP (JSON with padding) that uses Cross-Origin Resource Sharing can be used for cross-domain calls.