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 table list all the options available for configuring Ajax request.

Options Description
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.
complete A 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: function (data, status, xhr) {// success callback function
            $('p').append(data);
    }
});

<p></p>

In the above example, first parameter '/getData' of ajax() method is a url from which we want to retrieve the data.

By default ajax() method performs http GET request if option parameter does not include method option.

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) {   // success callback function
        $('p').append(data.firstName + ' ' + data.middleName + ' ' + data.lastName);
    },
    error: function (jqXhr, textStatus, errorMessage) { // error callback 
        $('p').append('Error: ' + errorMessage);
    }
});

<p></p>

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) {
        $('p').append('Error: ' + errorMessage);
    })

<p></p>

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) {
            $('p').append('Error' + errorMessage);
    }
});
<p></p>

In the above example, first parameter is a url which is used to submit the data. In the options parameter, we have specified a type option as a POST, so ajax() method will send http POST request. Also, we have specified data option as a JSON object containing data which will be submitted to the server.

So this way you can send GET, POST or PUT request using ajax() method.

Visit jQuery documentation to know more about ajax() method.

Points to Remember :
  1. $.ajax() method allows you to send asynchronous http requests to submit or retrieve data from the server without reloading the whole page.
  2. $.ajax() can be used to send http GET, POST, PUT, DELETE etc. request. It can retrieve any type of response from the server.
  3. Syntax: $.ajax(url,[options])
  4. Use option parameter to customize ajax request as per your need.