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.

OptionsDescription
acceptsThe content type sent in the request header that tells the server what kind of response it will accept in return.
asyncBy default, all requests are sent asynchronously. Set it false to make it synchronous.
beforeSendA callback function to be executed before Ajax request is sent.
cacheA boolean indicating browser cache. Default is true.
completeA callback function to be executed when request finishes.
contentTypeA string containing a type of content when sending MIME content to the server.Default is “application/x-www-form-urlencoded; charset=UTF-8”
crossDomainA boolean value indicating whether a request is a cross-domain.
dataA data to be sent to the server. It can be JSON object, string or array.
dataTypeThe type of data that you’re expecting back from the server.
errorA callback function to be executed when the request fails.
globalA Boolean indicating whether to trigger a global Ajax request handler or not. Default is true.
headersAn object of additional header key/value pairs to send along with request.
ifModifiedAllow 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.
isLocalAllow the current environment to be recognized as local.
jsonpOverride 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.
jsonpCallbackString containing the callback function name for a JSONP request.
mimeTypeString containing a mime type to override the XMLHttpRequest mime type.
passwordA password to be used with XMLHttpRequest in response to an HTTP access authentication request.
processDataA Boolean indicating whether data assigned to data option will be converted to a query string. Default is true.
statusCodeA JSON object containing numeric HTTP codes and functions to be called when the response has the corresponding code.
successA callback function to be executed when Ajax request succeeds.
timeoutA number value in milliseconds for the request timeout.
typeA type of http request e.g. POST, PUT and GET. Default is GET.
urlA string containing the URL to which the request is sent.
usernameA username to be used with XMLHttpRequest in response to an HTTP access authentication request.
xhrA callback for creating the XMLHttpRequest object.
xhrFieldsAn 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>

Try it

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>

Try it

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>

Try it

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.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *