jQuery provides support for asynchronous server interactions using Ajax API. jQuery Ajax is very easy to use and provides different methods as per need to quickly make AJAX calls to server.

$.ajax to send customized Ajax requests

One can customize AJAX call to server using this method. A sample code snippet for AJAX call is as below.


$.ajax({
  //URL to make AJAX request
  url:'/urlString',
  //Ajax request Method name
  method: 'GET', 
  //accepts defines reponse data client is expecting from server
  accepts: application/json, 
  //async default is true. Request should be async or not.
  async: true, 
  // beforeSend executes before ajax reqeust
  // beforeSend is mostly used to apply AJAX request settings.
  beforeSend: function(jqXHR, settings){
    //Operations to perform before sending ajax request.
    return true; // Return false will cancel the ajax request.
  },
  //cache defines ajax request needs to be cached in browser or not.
  // setting to false will force browsers to not caching the result of ajax request
  cache: true, 
  // contentType Defines content type of data which is being sent to the server. 
  // This is the content type server method is expecting to process data.
  contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
  //crossDomain Set to true if you are making ajax request to another domain.
  crossDomain: false,
  //data value can be key-value pairs or querystring.
  data: { firstname: "Hiral", lastname: "Patel" }, 
  //dataFilter is data pre-processing function.
  dataFilter: function(responseData, dataType){
    // This function executes upon successful response from the server.
    // This function can preprocess responseData and then success callback will execute.
    return responseData;
  },
  //dataType is the response Data Type. 
  // Parsing of Response data is as per the dataType
  // Default is intelligent guess to XML, JSON, Script or HTML. Datatype will try to parse the response data as defined in dataType and if parsing fails then it will trigge error.
  // text, html, xml, json, jsonp, and script are available options
  dataType: json, 
  // global Setting to false will not invoke global ajax operation like ajaxStart() and ajaxStop() functions
  global: true,
 //headers defines additional headers in key-value pairs to be added in reqeust header
  headers: {}, 
  // statusCode method executes if specific status code is returned in the response.
  statusCode: {
    404: function() {
      alert( "page not found" );
  },
  //timeout in ms 
  timeout: 200000 
})
.done(function(responseData, textStatus, jqXHR){
    // This function will executes if response is success
    // responseData will be formatted as per the dataFilter or dataType if specified
    // Handle success scenario of ajax request here
})
.fail(function(jqXHR, textStatus, errorThrown){
    // This function will executes if response is failure
    // jqXHR is the object describing error's detailed information
    // textStatus can be null, "timeout", "error", "abort", and "parsererror"
    // When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."
    // Handle error scenario of ajax request here
})
.always(function(jqXHR, statusText){
    // This method executes after success and error callbacks 
    // statusText can be "success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror"
    return true;
});
  

Above format is underlying structure of all different variants of jQuery Ajax methods. Above format is used to send customized ajax request to the server.

Below image shows the execution of jQuery ajax callback functions execution order.
jQuery Ajax Call back function flow

$.ajaxSetup() to set default Ajax setting for all future requests

$.ajaxSetup() is used to setup default Ajax settings to be used for all future requests.


$.ajaxSetup({
  cache: false // This will not cache any Ajax request's response from server.
});
  

jQuery Ajax Shorthand Methods

jQuery provides methods to perform common operations without writing too much code.

$.get()

$.get( url [, data ] [, success ] [, dataType ]) method loads data from server using HTTP GET request. Read More


$.get( "test.cgi", { name: "John", time: "2pm" }, function( data ) {
  alert( "Data Loaded: " + data );
})
.done(function( data ) {
  alert(" Second Success " + data );
});
.fail(function() {
  alert( "error" );
})
.always(function() {
  alert( "finished" );
});
  

$.getJSON()

.getJSON( url [, data ] [, success ] ) method loads JSON data from server using HTTP GET request. Read More


$.getJSON( "test.js", { name: "John", time: "2pm" } )
.done(function( json ) {
  console.log( "JSON Data: " + json.users[ 3 ].name );
})
.fail(function( jqxhr, textStatus, error ) {
  var err = textStatus + ", " + error;
  console.log( "Request Failed: " + err );
});
  

$.getScript()

.getScript( url [, success ] ) method loads js file from server using HTTP GET reqeust. Read More


$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
})
.done(function(data, textStatus, jqxhr) {
  // second success call back function.
  console.log( data ); // Data returned
})
.fail(function( jqxhr, textStatus, error ) {
  var err = textStatus + ", " + error;
  console.log( "Request Failed: " + err );
});
  

$.post()

.post( url [, data ] [, success ] [, dataType ] ) method load data from server using HTTP POST request. Read More


$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
  alert( "Data Loaded: " + data );
});
  

$.load()

.load( url [, data ] [, complete ] ) method load data from server and append it into selector. If data is passed then jQuery sends Ajax HTTP POST request, otherwise jQuery sends Ajax HTTP GET request. Read More


$( "#result" ).load( "ajax/test.html #container" );
// Above line will load test.html and find DOM element with ID = container. 
//This element along with its inner content is inserted into the element with ID = result of a document.
  

Global AJAX Event Handlers

Global AJAX event handlers are used to specifies settings to be applied on all ajax requests. global: false is used in $.ajax request to avoid call to global ajax event handlers.

$.ajaxComplete()

$.ajaxComplete() global event handler executes after AJAX request execution is complete. This method executes on every AJAX requests irrespective of response is success or failure. Read More


$( document ).ajaxComplete(function( event, xhr, settings ) {
  $( "#msg" ).append("Request Complete. Response Text is "+ xhr.responseText);
});
  

$.ajaxSuccess()

$.ajaxSuccess() global event handler executes when jquery ajax request completes successfully. This method executes on every Ajax request for which response is successful. Read More


$( document ).ajaxSuccess(function( event, request, settings ) {
  $( "#msg" ).append("Successful AJAX request.");
});
  

$.ajaxError()

$.ajaxError() global event handler executes when AJAX request completes with an Error. This method executes on every AJAX request for which response is error. Read More


$( document ).ajaxError(function( event, request, settings, thrownError ) {
  $( "#msg" ).append("Error requesting URL " + settings.url);
});
  

$.ajaxSend()

$.ajaxSend() global event handler executes when AJAX request is about to sent. This method executes just before every AJAX request. Read More


$( document ).ajaxSend(function( event, request, settings ) {
  $( "#msg" ).append( "Starting request at " + settings.url);
});
  

$.ajaxStart()

$.ajaxStart() global event handler executes when AJAX request start and NO OTHER ajax request is active. This method executes when the FIRST Ajax request begins. Read More


$( document ).ajaxStart(function() {
  $( "#loading" ).show();
});
  

$.ajaxStop()

$.ajaxStop() global event handler executes when ALL Ajax request stopped. Whenever Ajax request completes, jQuery checks for any other active ajax requests. If no other ajax request is going on, then jquer executes event handlers registered using $.ajaxStop(). This method executes only when ALL Ajax requests have completed. Read More


$( document ).ajaxStop(function() {
  $( "#loading" ).hide();
});
  

References

jQuery Documentation