How to Use jQuery’s $.ajax() Function

By Aurelio De Rosa

Without any doubt Ajax has taken web development by storm and it’s one of the most successful paradigms ever. In my article An Introduction to jQuery’s Shorthand Ajax Methods, I discussed some of jQuery’s most used Ajax shorthand methods: $.get(), $.post(), and $.load(). They are convenient methods for making Ajax requests in a few lines of code.

Sometimes, we need more control over the Ajax calls we want to make. For example, we want to specify what should happen in case an Ajax call fails or we need to perform an Ajax request but its result is only needed if retrieved within a certain amount of time. In such situations, we can rely on another function provided by jQuery, called $.ajax(), that is the topic of this tutorial.

The $.ajax() Function

The jQuery $.ajax() function is used to perform an asynchronous HTTP request. It was added to the library a long time ago, existing since version 1.0. The $.ajax() function is what every function discussed in the previously mentioned article calls behind the scene using a preset configuration. The signatures of this function are shown below:

$.ajax(url[, options])

The url parameter is a string containing the URL you want to reach with the Ajax call, while options is an object literal containing the configuration for the Ajax request.

In its first form, this function performs an Ajax request using the url parameter and the options specified in options. In the second form, the URL is specified in the options parameter, or can be omitted in which case the request is made to the current page.

The list of the options accepted by this function, described in the next section, is very long. So, I’ll keep their description short. In case you want to study in-depth their meaning, you can refer to the official documentation of $.ajax().

The option Parameter

There are a lot of different options you can specify to bend $.ajax() to your need. In the list below you can find their names and their description sorted in alphabetic order:

  • accepts: The content type sent in the request header that tells the server what kind of response it will accept in return
  • async: Set this options to false to perform a synchronous request
  • beforeSend: A pre-request callback function that can be used to modify the jqXHR object before it is sent
  • cache: Set this options to false to force requested pages not to be cached by the browser
  • complete: A function to be called when the request finishes (after success and error callbacks are executed)
  • contents: An object that determines how the library will parse the response
  • contentType: The content type of the data sent to the server
  • context: An object to use as the context (this) of all Ajax-related callbacks
  • converters: An object containing dataType-to-dataType converters
  • crossDomain: Set this property to true to force a cross-domain request (such as JSONP) on the same domain
  • data: The data to send to the server when performing the Ajax request
  • dataFilter: A function to be used to handle the raw response data of XMLHttpRequest
  • dataType: The type of data expected back from the server
  • error: A function to be called if the request fails
  • global: Whether to trigger global Ajax event handlers for this request
  • headers: An object of additional headers to send to the server
  • ifModified: Set this option to true if you want to force the request to be successful only if the response has changed since the last request
  • isLocal: Set this option to true if you want to force jQuery to recognize the current environment as “local”
  • jsonp: A string to override the callback function name in a JSONP request
  • jsonpCallback: Specifies the callback function name for a JSONP request
  • mimeType: A string that specifies the mime type to override the XHR mime type
  • password: A password to be used with XMLHttpRequest in response to an HTTP access authentication request
  • processData : Set this option to false if you don’t want that the data passed in to the data option (if not a string already) will be processed and transformed into a query string
  • scriptCharset: Sets the charset attribute on the script tag used in the request but only applies when the “script” transport is used
  • statusCode: An object of numeric HTTP codes and functions to be called when the response has the corresponding code
  • success: A function to be called if the request succeeds
  • timeout: A number that specifies a timeout (in milliseconds) for the request
  • traditional: Set this to true if you wish to use the traditional style of param serialization
  • type: The type of request to make, which can be either “POST” or “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 to set on the native XHR object

That was pretty long, isn’t it? Well, as developers you probably have stopped reading this list at the fifth or sixth element I guess, but that’s fine. The next section will be more exciting because we’ll put the $.ajax() function and some of these options into action.

Putting It All Together

In this section we’ll see this function and some of its options in action.

A First Example of $.ajax()

We’ll start with a simple demo that reproduces the same code we developed in the previous article, but this time we’ll adopt $.ajax(). The code I’m talking about is shown below for your commodity:

$('#main-menu a').click(function(event) {
   $('#main').load(this.href + ' #main *', function(responseText, status) {
      if (status === 'success') {
         $('#notification-bar').text('The page has been successfully loaded');
      } else {
         $('#notification-bar').text('An error occurred');

Updating this snippet to employ the $.ajax() function, we obtain the code shown below:

$('#main-menu a').click(function(event) {
   $.ajax(this.href, {
      success: function(data) {
         $('#main').html($(data).find('#main *'));
         $('#notification-bar').text('The page has been successfully loaded');
      error: function() {
         $('#notification-bar').text('An error occurred');

Here you can see that I used the first form of the function. I’ve specified the URL to send the request to as the first parameter and then an object of options as the second parameter. The latter takes advantage of just two of the several properties discussed in the previous section: success and error to specify what to do in case of success or failure of the request respectively.

Retrieving a Talk From Using $.ajax()

The second example I want to discuss creates a JSONP request to retrieve some information from a service called The latter is a website where event attendees can leave feedback on an event and its sessions. Specifically, I’m going to create a snippet of code that, using the $.ajax() function, retrieves the title and the description of my talk Modern front-end with the eyes of a PHP developer.

The code to achieve this goal is as follows:

   url: '',
   data: {
      format: 'json'
   error: function() {
      $('#info').html('<p>An error has occurred</p>');
   dataType: 'jsonp',
   success: function(data) {
      var $title = $('<h1>').text(data.talks[0].talk_title);
      var $description = $('<p>').text(data.talks[0].talk_description);
   type: 'GET'

In the snippet above, I employed several of the properties discussed. First of all, you can see that I’m using the second form of $.ajax(), which allows to specify the URL to which the request is sent as a property (url) of the object literal. Because the’s API accepts a JSONP request, in the code above I’m setting the type of request I want to use by specifying the dataType property. Then, I used the data property to define the format’s type that I want to obtain from the server as required by the API. However, the latter requires this data as part of the query string of a GET request, hence I’m also specifying the type property setting GET as its value. Finally, I wrote an error callback to display a message in case of error, and a success callback to display the title and the description of the talk in case of success.

A live demo of this code is shown below and is also available as a JSfiddle:

Note: in case you need a library to embed a talk from, I developed a library called JoindIn.js.


In this tutorial we’ve discussed the most powerful of the Ajax functions offered by jQuery, $.ajax(). It allows you to perform Ajax request with a lot of control over how the request is sent to the server and how the response is processed. Thanks to this function you have the tools you need to satisfy every need your project may have in case none of the shorthand functions are a good fit.

To have an even better understanding of the potential of this function, I encourage you to play with the code samples, and to try to modify it to use some other options accepted by the options parameter. Have fun!

  • Superb! Thanks a lot.

    • Aurelio De Rosa

      Hi Fernando.

      I’m glad you enjoyed the article. Keep reading!

  • Matt Harting

    The jQuery API now lists the success, error and complete methods as deprecated and recommends using done, fail and always instead.

  • You are not fully explained about an ajax as for me. You forgot about promises and it’s very important. This post can be helpful for beginners =)

  • The success, error, and complete *promise methods* are deprecated, but the corresponding option callbacks are not. Still, I prefer to use the done, fail, and always methods myself.

    • Aurelio De Rosa

      Thank you for commenting Karl. You’re always welcome!

  • Aurelio De Rosa

    Hi Matt.

    As Karl has written, they are not deprecated. Besides, for very simple cases like those I’ve shown in the article I prefer to stick with the callbacks. On the contrary, I prefer to use the promise methods when I have to manage more complex cases like waiting more than one asynchronous operation.

    • Shailesh Prajapati

      Hi Aurelio.. nice example of ajax as well as jquery’s ajax

  • Aurelio De Rosa

    Hi Denis. I hadn’t forget about promises. I purposely avoided the topic because explaining what Promises are would require an article on its own. In this I want readers to focus on what the $.ajax() method is, what are its options, and how and why a developer should use it.

  • Bnny

    Ajax() feedback and notice for beginners:
    (1) I would show the beginners also how to return value to the caller of the function where the ajax call is wrapped. To show why its still important to keep the Async:true in extra thought.
    (2) To keep flag-method in mind so an ajax call wont run unwanted second time.
    (3) Sometimes a call to a file can fail, its normal.. maybe a beginner wants to have 3 attempts instead of one. It would be nice if you demonstrate that too.

    When you want to explain Ajax(), you should also have to explain how to use it in full development at still basic lvl.

  • tom

    how to use xhr in ajax function

  • Daniel

    How to get Json data on page load OR get url generated from Json data on click event

    I’m testing an existing website and I need to pick up the url of a link and the href text = “#”.

    If I click on the link, whatever it is opens then displays a perfectly normal URL in the browser, so the website is somehow translating “#” into a proper URL. I have several hundred items, all referenced by “#”, but all opening completely different items when you click on them.

  • jeff

    hey awesome article! it simplified a lot of concepts for me ;)

  • mcbeth

    Hi. I tried to use the code with ‘’ but it returns ‘error’ . Any idea why ?

  • JUN

    Hi there what is the simplest way to use ajax when using post and get method with a touch of php when receiving the data? Thanks

  • Leandro Martins Guimarães

    It’s better to handle Ajax errors with something like this:

    error: function(jqXHR, textStatus, errorThrown) {
    alert(textStatus + ‘: ‘ + errorThrown);

    • Eutychus Towett

      Awesome man. That comment helped a lot.

  • EvilDarthMaul

    This is by far one of the most complete and easy to follow articles I’ve found dealing with jQuery ajax. Gracias Aurelio!

  • CityLims

    Yikes with that last example. Why would you organize your ajax call that way? It’s not technically wrong but goes totally against the semantic web and is not readable.
    Why would you put the type at the bottom, and jam the error handler randomly between the datatype settings option? This is terrible pattern, and if someone on my team did this I would slap them.

    this is how jquery docs order ajax calls.

  • disqus_IzvrswPfd3

    How can I set my file://Users …. /index.html link as main(for example: and when I hit the buttons on my HTML page keep the address how it is but load the JSON data?

  • Jitfender

    Thank you. This topic is very useful for me to start Ajax.

  • Nirav Patel

    Thank You .. its very helpful for beginner.


    Thanks for the great work, Ajax seems simpler and more flexible with jQuery.

  • What do I supply for dataType when I am accessing an instance of a class object >> i.e. obj.Name, obj.Address, obj.City

Get the latest in JavaScript, once a week, for free.