Overview of jQuery Ajax Methods
Let us first distribute the words jQuery and ajax and know the literal meaning of each of these. JQuery is the javascript library which is very lightweight, and it only says us write less do more. But before coming to jQuery, you must know the basics of html, CSS, and javascript. The main task of jQuery is to make the developer task easy to render Javascript on the browser with very much ease and in very little time. In an easy word, we can say that jQuery turns a heavy line of javascript code into a single line of code using jQuery methods. jQuery also simplifies the complicated javascript code, dom-manipulation and ajax call.
Features of jQuery Ajax Methods
Following features are available in jQuery, which are listed below :
- HTML event methods
- CSS manipulation
- DOM/HTML manipulation
- AJAX
- Effects and animations
- Utilities
I think now you have much basic knowledge about jQuery, so let’s come to the meaning of AJAX. Ajax stands for asynchronous javascript and XML( extensive markup language ). Ajax is the simplest and easiest way to create dynamic web pages. Ajax just says us that exchange data without refreshing the web page. It means that we can exchange a small amount of data with the server without refreshing the page, or in other words, we can say ajax update the webpage without reloading the page. In classic web pages, they need to reload the whole page if they want to exchange data with the server or update the web page. Let us discuss in short how does it work.
So basically, what happens, whenever an event occurs browser creates an XMLHttpRequest object and sends an HttpRequest to the server. Then the server process this HTTPRequest and create a response, and send data back to the browser. Now, the browser process the returned data using javascript and update the page content.
So after understanding both of these terms, now it’s time to discuss the topic. So what is jQuery ajax? jQuery provides many methods that help in ajax server-side updating of web pages. The syntax for jQuery ajax is jQuery.ajax( url [, settings ]), where URL is a string from which a request is sent. The setting is the type of plain object. The jQuery ajax methods just provides some valuable resourceful functionality to the ajax in jQuery. An ajax has an url and an option like this :
$.ajax(url);
$.ajax(url,[options]);
Here url is a type of string through which we can send and receive data, and options are ajax request configuration. There are many options available in jQuery ajax.
Let’s discuss some of them.
- Accepts: it tells the server that what kind of response in return it would accept.
- Async: we have to set it false if we want to send the data synchronously because, in the default, data is sent or received asynchronously.
- BeforeSend: it means that before an ajax request is sent, a callback function needs to be executed.
- Cache: by default, it is true. A browser cache is shown through Boolean.
- Complete : when request is finished, a callback function need to executed.
- contentType : Default contentType is “application/x-www-form-urlencoded; charset=UTF-8”.
- crossDomain : a boolean value represents whether the processed request is cross domain or not.
- Data:The data is in the form of an array, string,g or object that needs to be sent to the server.
- dataType: it is the type of data u r expecting the server to return.
- Error: it means that a callback function needs to be executed when the request fails.
- Global: by default, it is true. It gives a Boolean response of whether to activate a global request or not.
- Headers: an object needs to be sent along with the request.
- ifModified: if the request has changed from the last updated requested then only the response is valid.
- isLocal: it allows the current or present development environment to be recognized as
- Jsonp: in a jsonp request, it overrides the callback function.
- jsonpCallback: it is a type of string that contains a jsonprequest in the name of the callback function.
- mimeType: it contain a mime type to override xmlhttprequest .
- password: it is used in the http authentication request.
- processData: by default, it is true, it only gives the Boolean response whether data assigned to the data option should be converted to a query string or not.
- statusCode: it is a numeric http request code that responds according to the corresponding code response.
- Success: if the httprequest has succeeded, then only the callback function should be executed.
- Timeout: it is the timeout value of response in milliseconds.
- Type: it is the type of httprequest like GET, PUT, POST. By default, it is GET.
- url: it is the string that contains url where data need to be sent.
- Username : it is also used in XMLHTTP authentication request.
- Xhr: it is the callback function to create an xmlhttprequest object.
- xhrFields: it is a pair set value of fieldName-fieldValue.
Methods of jQuery Ajax
Now let’s discuss some jQuery ajax methods with its syntax & examples. Below are the mentioned jQuery methods.
1. jQuery.get( url, [data], [callback], [type] )
This method helps us in loading data from the server using the GET HTTP Request. This method also returns XMLHttpRequest object.
- url – it is the string which contains url through which data is sent.
- Data –This is the optional parameter that contains the key and value pair sent to the server.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
- Type – it is also an optional parameter which returns a type of data after callback function such as html, xml, json, text, jsonp.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
$.get(
"result.php",
{ name: "Zara2" },
function(data) {
$('#stage2').html(data);
}
);
});
});
2. jQuery.getJSON( url, [data], [callback] )
This method loads json data from the server through the GET HTTP Request.
- url – it is the string that contains url through which data is sent.
- Data – This is the optional parameter that contains the key and value pair sent to the server.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
$.getJSON('result.json', function(jd) {
$('#stage2').html('<p> Name: ' + jd.name + '</p>');
$('#stage2').append('<p>Age : ' + jd.age+ '</p>');
$('#stage2').append('<p> Sex: ' + jd.sex+ '</p>');
});
});
});
3. jQuery.getScript( url, [callback] )
This method loads and execute the javascript file through HTTP GET Request.
- url – it is the string that contains url through which data is sent.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
$.getScript('result.js', function(jd) {
// Call custom function defined in script
CheckJS();
});
});
});
4. jQuery.post( url, [data], [callback], [type] )
This methods loads a web page using HTTP POST Request.
- url – it is the string which contains url through which data is sent.
- Data –This is the optional parameter that contains key and value pair sent to the server.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
- Type – it is also an optional parameter that returns a type of data after callback function such as html, xml, json, text, jsonp.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
$.post(
"result.php",
{ name: "Zara" },
function(data) {
$('#stage2').html(data);
}
);
});
});
5. load( url, data, callback)
This method loads the data or object from the server and replaces the returned html after success request to the matched element.
- url – it is the string that contains url through which data is sent.
- Data – This is the optional parameter that contains the key and value pair sent to the server.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example:
$(document).ready(function() {
$("#drive2r").click(function(event){
$('#stage2').load('result.html');
});
});
6. serialize( )
This method helps to serialize a set of input elements into a set of the data array. There is no parameter in this jQuery ajax method. For example-
$(document).ready(function() {
$("#driver2").click(function(event){
$.post(
"/jquery/serialize.php",
$("#testform1").serialize(),
function(data) {
$('#stage2').html(data);
}
);
var str = $("#testform1").serialize();
$("#stage3").text(str);
});
});
7. serializeArray( )
This method functions the same like serialize method; the only difference is that it returns json data structure. This method also does not have any parameters. For example-
$(document).ready(function() {
$("#driver2").click(function(event){
$.post(
"/jquery/serialize.php",
$("#testform1").serializeArray(),
function(data) {
$('#stage2').html(data);
}
);
var fields = $("#testform1").serializeArray();
$("#stage3").empty();
jQuery.each(fields, function(i, field){
$("#stage3").append(field.value + " ");
});
});
});
8. ajaxComplete( callback )
This method stitches a function when the callback function is executed successfully.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example :
$(document).ready(function() {
$("#driver2").click(function(event){
$('#stage2').load('result.html');
});
$(document).ajaxComplete(function(event, request, settings){
$("#stage3").html("<h1>Request Complete.</h1>");
});
});
9. ajaxStart( callback )
This method attaches a function to be executed before the ajax request start.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example:
$(document).ready(function() {
/* Global variable */
var count = 2;
$("#driver2").click(function(event){
$('#stage2').load('result.html');
});
/* Gets called when the request starts */
$(document).ajaxStart(function(){
count++;
$("#stage3").html("<h1>Starts, Count :" + count + "</h1>");
});
/* Gets called when request complete */
$(document).ajaxComplete(function(event,request,set){
count++;
$("#stage4").html("<h1>Completes,Count:" + count + "</h1>");
});
});
10. ajaxError( callback)
This method attaches a function that is executed whenever the ajax request fails. This is also a type of ajax event.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example:
$(document).ready(function() {
$("#driver2").click(function(event){
/* Assume result.text does not exist. */
$('#stage12').load('/jquery/result.text');
});
$(document).ajaxError(function(event, request, settings ){
$("#stage22").html("<h1>Error in front page.</h1>");
});
});
11. ajaxSend( callback)
This method calls a function just after the ajax request is sent. This is also an ajax event.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example:
$(document).ready(function() {
var count = 0;
$("#drive2r").click(function(event){
$('#stage1').load('result.html');
});
$(document).ajaxStart(function(){
count++;
$("#stage12").html("<h1>Starts, Count :" + count + "</h1>");
});
$(document).ajaxSend(function(evt, req, set){
count++;
$("#stage23").html("<h1>Sends, Count :" + count + "</h1>");
$("#stage23").append("<h1>URL :" + set.url + "</h1>");
});
$(document).ajaxComplete(function(event,request,settings){
count++;
$("#stage33").html("<h1>Completes, Count :" + count + "</h1>");
});
});
12. ajaxStop( callback)
This method attaches a function which is executed just after the ajax request has ended.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example:
$(document).ready(function() {
var count = 0;
$("#driver2").click(function(event){
$('#stage1').load('result.html');
});
$(document).ajaxStart(function(){
count++;
$("#stage12").html("<h1>Starts, Count :" + count + "</h1>");
});
$(document).ajaxSend(function(evt, req, set){
count++;
$("#stage22").html("<h1>Sends, Count :" + count + "</h1>");
$("#stage22").append("<h1>URL :" + set.url + "</h1>");
});
$(document).ajaxComplete(function(event,request,settings){
count++;
$("#stage3").html("<h1>Completes, Count :" + count + "</h1>");
});
$(document).ajaxStop(function(event,request,settings){
count++;
$("#stage44").html("<h1>Stops, Count :" + count + "</h1>");
});
});
13. ajaxSuccess( callback)
This method calls a function just after the ajax request is completed successfully.
- Callback is also an optional parameter that means a function to be executed when the ajax request is succeeded.
Example:
$(document).ready(function() {
var count = 2;
$("#driver2").click(function(event){
$('#stage2').load('result.html');
});
$(document).ajaxStart(function(){
count++;
$("#stage12").html("<h1>Starts, Count :" + count + "</h1>");
});
$(document).ajaxSend(function(evt, req, set){
count++;
$("#stage22").html("<h1>Sends, Count :" + count + "</h1>");
$("#stage22").append("<h1>URL :" + set.url + "</h1>");
});
$(document).ajaxComplete(function(event,request,settings){
count++;
$("#stage32").html("<h1>Completes,Count:" + count + "</h1>");
});
$(document).ajaxStop(function(event,request,settings){
count++;
$("#stage42").html("<h1>Stops, Count :" + count + "</h1>");
});
$(document).ajaxSuccess(function(event,request,settings){
count++;
$("#stage52").html("<h1>Success,Count :" + count + "</h1>");
});
});
Now lets come to the importance of jQuery ajax methods which are listed below :
- It is cross-browser compatible and supports nearly all the browser.
- It is the simplest method to use when updating the content of the webpage without reloading the page.
- It has the power to send POST and GET Requests.
- It has the ability to load html, json, xml or scripts.
Recommended Articles
This is a guide to jQuery Ajax Methods. Here we discuss the basic concept with some methods of jQuery Ajax with the Syntax and Examples. You may also look at the following data analysis course to learn more –