AJAX & jQuery -Ajax Tutorial
AJAX
- is a web development technique for creating interactive web applications. If you know JavaScript, HTML, CSS, and XML, then you need to spend just one hour to start with AJAX.
- Asynchronous JavaScript and XML, while not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that describes a “new” approach to using a number of existing technologies together, including HTML or XHTML, CSS, JavaScript, DOM, XML, and most importantly the
XMLHttpRequest
object.
When these technologies are combined in the Ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions. - JavaScript includes features of sending asynchronous http request using XMLHttpRequest object. Ajax is about using this ability of JavaScript to send asynchronous http request and get the xml data as a response (also in other formats) and update the part of a web page (using JavaScript) without reloading or refreshing entire web page.
The following figure illustrates the Ajax functionality.
Why to Learn Ajax?
AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
- Ajax uses XHTML for content .
- Ajax uses CSS for presentation .
- Ajax uses JavaScript along with Document Object Model for dynamic content display.
- Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server.
- With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
- XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.
- AJAX is a web browser technology independent of web server software.
- A user can continue to use the application while the client program requests information from the server in the background.
- Natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger.
- Data-driven as opposed to page-driven.
AJAX is Based on Open Standards
AJAX is based on the following open standards −
- Browser-based presentation using HTML and Cascading Style Sheets (CSS).
- Data is stored in XML format and fetched from the server.
- Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
- JavaScript to make everything happen.
AJAX cannot work independently. It is used in combination with other technologies to create interactive webpages.
* JavaScript
- Loosely typed scripting language.
- JavaScript function is called when an event occurs in a page.
- Glue for the whole AJAX operation.
* DOM
- API for accessing and manipulating structured documents.
- Represents the structure of XML and HTML documents.
* CSS
- Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript
* XMLHttpRequest
- JavaScript object that performs asynchronous interaction with the server.
Sending an XMLHttpRequest
A common JavaScript syntax for using the XMLHttpRequest object looks much like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById(“demo”).innerHTML = xhttp.responseText;
}
};
xhttp.open(“GET”, “filename”, true);
xhttp.send();
Example Explained :
The first line in the example above creates an XMLHttpRequest object:
var xhttp = new XMLHttpRequest();
The onreadystatechange property specifies a function to be executed every time the status of the XMLHttpRequest object changes:
xhttp.onreadystatechange = function()
When readyState property is 4 and the status property is 200, the response is ready:
if (this.readyState == 4 && this.status == 200)
The responseText property returns the server response as a text string.
The text string can be used to update a web page:
document.getElementById(“demo”).innerHTML = xhttp.responseText;
The onreadystatechange Property
- The readyState property holds the status of the XMLHttpRequest.
- The onreadystatechange property defines a function to be executed when the readyState changes.
- The status property and the statusText property holds the status of the XMLHttpRequest object.
Ready State :
Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is readystatus
status :
100: "Continue"
200: "OK"
400: "Bad Request"
401: "Unauthorized"
403: "Forbidden"
404: "Page not found"
500: "Internal Server Error"
statusText :
Returns the status-text
- “OK”
- “Not Found”
The onreadystatechange function is called every time the readyState changes.
jQuery — Ajax
JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.
Advantages of jQuery Ajax
- Cross-browser support
- Simple methods to use
- Ability to send GET and POST requests
- Ability to Load JSON, XML, HTML or Scripts
Methods :
The jQuery library includes various methods to send Ajax requests. These methods internally use XMLHttpRequest object of JavaScript.
- ajax() : Sends asynchronous http request to the server .
- get() : Sends http GET request to load the data from the server .
- Post() : Sends http POST request to submit or load the data to the server.
- getJSON() : Sends http GET request to load JSON encoded data from the server.
- getScript() : Sends http GET request to load the JavaScript file from the server and then executes it.
- load() : Sends http request to load the html or text content from the server and add them to DOM element(s).
Let’s look at an overview of important jQuery Ajax methods in the next section.
jQuery ajax() Method
The jQuery ajax() method provides core functionality of Ajax in jQuery. It sends asynchronous HTTP requests to the server.
Syntax:
$.ajax(url);$.ajax(url,[options]);
Parameter description:
- url: A string URL to which you want to submit or retrieve the data
- options: Configuration options for Ajax request. An options parameter can be specified using JSON format. This parameter is optional.
The following list all the options available for configuring Ajax request.
- accepts : The content type sent in the request header that tells the server what kind of response it will accept in return.
- async : By default, all requests are sent asynchronously. Set it false to make it synchronous.
- beforeSend : A callback function to be executed before Ajax request is sent.
- cache : A boolean indicating browser cache. Default is true.completeA callback function to be executed when request finishes.
- contentType : A string containing a type of content when sending MIME content to the server.Default is “application/x-www-form-urlencoded; charset=UTF-8”.
- crossDomain : A boolean value indicating whether a request is a cross-domain.
- data : A data to be sent to the server. It can be JSON object, string or array.
- dataType : The type of data that you’re expecting back from the server.
- error : A callback function to be executed when the request fails.
- global : A Boolean indicating whether to trigger a global Ajax request handler or not. Default is true.
- headers : An object of additional header key/value pairs to send along with request.
- ifModified : Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false.
- isLocal : Allow the current environment to be recognized as local.
- jsonp : Override the callback function name in a JSONP request. This value will be used instead of ‘callback’ in the ‘callback=?’ part of the query string in the url.
- jsonpCallback : String containing the callback function name for a JSONP request.
- mimeType : String containing a mime type to override the XMLHttpRequest mime type.
- password : A password to be used with XMLHttpRequest in response to an HTTP access authentication request.
- processData : A Boolean indicating whether data assigned to data option will be converted to a query string. Default is true.
- statusCode : A JSON object containing numeric HTTP codes and functions to be called when the response has the corresponding code.
- success : A callback function to be executed when Ajax request succeeds.
- timeout : A number value in milliseconds for the request timeout.
- type : A type of http request e.g. POST, PUT and GET. Default is GET.
- url : A string containing the URL to which the request is sent.
- username : A username to be used with XMLHttpRequest in response to an HTTP access authentication request.
- xhr : A callback for creating the XMLHttpRequest object.
- xhrFields : An object of fieldName-fieldValue pairs to set on the native XMLHttpRequest object.
Let’s see how to send http requests using $.ajax() (or jQuery.ajax()) method.
Send Ajax Request
The ajax() methods performs asynchronous http request and gets the data from the server. The following example shows how to send a simple Ajax request.
Example: jQuery Ajax Request
$.ajax('/jquery/getdata', // request url
{
// success callback Function
success: function (data, status, xhr) {
$('div').append(data);
}
});<div></div>
In the above example, first parameter ‘/getData’ of ajax() method is a url from which we want to retrieve the data.
The second parameter is options parameter in JSON format where we have specified callback function that will be executed when request succeeds. You can configure other options as mentioned in the above table.
The following example shows how to get the JSON data using ajax() method.
Example: Get JSON Data
$.ajax('/jquery/getjsondata',
{
dataType: 'json', // type of response data
timeout: 500, // timeout milliseconds
success: function (data,status,xhr) {
$('p').append(data.firstName + ' ' + data.middleName + ' ' + data.lastName);
},
error: function (jqXhr, textStatus, errorMessage) {
$('div').append('Error: ' + errorMessage);
}
});<div></div>
In the above example, first parameter is a request url which will return JSON data. In the options parameter, we have specified dataType and timeout options. The dataType option specifies the type of response data, in this case it is JSON. The timeout parameter specifies request timeout in milliseconds. We have also specified callback functions for error and success.
The ajax() method returns an object of jQuery XMLHttpRequest. The following example shows how to use jQuery XMLHttpRequest object.
Example: ajax() Method
var ajaxReq = $.ajax('GetJsonData', {
dataType: 'json',
timeout: 500
});ajaxReq.success(function (data, status, jqXhr) {
$('p').append(data.firstName + ' ' + data.middleName + ' ' + data.lastName);
})
ajaxReq.error(function (jqXhr, textStatus, errorMessage) {
$('div').append('Error: ' + errorMessage);
})<div></div>
Send Http POST request using ajax()
The ajax() method can send all type of http requests. The following example sends http POST request to the server.
Example: Send POST Request
$.ajax('/jquery/submitData', {
type: 'POST', // http method
data: { myData: 'This is my data.' }, // data to submit
success: function (data, status, xhr) {
$('p').append('status: ' + status + ', data: ' + data);
},
error: function (jqXhr, textStatus, errorMessage) {
$('div').append('Error' + errorMessage);
}
});
<div></div>
Query get() Method
The jQuery get() method sends asynchronous http GET request to the server and retrieves the data.
Syntax:
$.get(url, [data],[callback]);
Parameters Description:
- url: request url from which you want to retrieve the data
- data: data to be sent to the server with the request as a query string
- callback: function to be executed when request succeeds
The following example shows how to retrieve data from a text file.
Example: jQuery get() Method
$.get('/data.txt', // url
function (data, textStatus, jqXHR) { // success callback
alert('status: ' + textStatus + ', data:' + data);
});
jQuery post() Method
The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response.
Syntax:
$.post(url,[data],[callback],[type]);
Parameter Description:
- url: request url from which you want to submit & retrieve the data.
- data: json data to be sent to the server with request as a form data.
- callback: function to be executed when request succeeds.
- type: data type of the response content.
Let’s see how to submit data and get the response using post() method. Consider the following example.
Example: jQuery post() Method
$.post('/jquery/submitData', // url
{ myData: 'This is my data.' }, // data to be submit
function(data, status, jqXHR) {// success callback
$('p').append('status: ' + status + ', data: ' + data);
})<p></p>
jQuery load() Method
The jQuery load() method allows HTML or text content to be loaded from a server and added into a DOM element.
Syntax:
$.load(url,[data],[callback]);
Parameters Description:
- url: request url from which you want to retrieve the content
- data: JSON data to be sent with request to the server.
- callback: function to be executed when request succeeds
The following example shows how to load html content from the server and add it to div element.
Example: Load HTML Content
$('#msgDiv').load('/demo.html');
<div id="msgDiv"></div>
In the above example, we have specified html file to load from the server and add its content to the div element.
Note : If no element is matched by the selector then Ajax request will not be sent.
The load() method allows us to specify a portion of the response document to be inserted into DOM element. This can be achieved using url parameter, by specifying selector with url separated by one or multiple space characters as shown in the following example.
Example: jQuery load() Method
$('#msgDiv').load('/demo.html #myHtmlContent');<div id="msgDiv"></div>
In the above example, content of the element whose id is myHtmlContent, will be added into msgDiv element.
Events :
The jQuery library also includes following events which will be fired based on the state of the Ajax request.
- ajaxComplete() : Register a handler function to be called when Ajax requests complete.
- ajaxError(): Register a handler function to be called when Ajax requests complete with an error.
- ajaxSend(): Register a handler function to be called before Ajax request is sent.
- ajaxStart(): Register a handler function to be called when the first Ajax request begins.
- ajaxStop(): Register a handler function to be called when all the Ajax requests have completed.
- ajaxSuccess(): Register a handler function to be called when Ajax request completes successfully.