How AJAX Works Using the jQuery Library

The jQuery ajax() method provides core functionality of AJAX in jQuery. It sends asynchronous HTTP requests to the server.

The standard way of making an AJAX call using jQuery is rather simple – by using the $.ajax() function:

<script>
$.ajax(
  '/jquery/getdata',
  {
      success: function(data) {
        alert('AJAX call was successful!');
        alert('Data from the server' + data);
      },
      error: function() {
        alert('There was some error performing the AJAX call!');
      }
   }
);
</script>

As you already known, the $ sign is used to refer to a jQuery object.

In the above example, the first parameter is  string URL to which you want to submit or retrieve the data.

The second parameter is the JSON format. By default, ajax() method performs http GET request if option parameter does not include method option.

In most cases, we will need to specify the success and error callbacks. The success callback will be called after the successful completion of the Ajax call. On the other hand, the failure callback will be called if something goes wrong and there was an issue performing the AJAX call.

Using Promises for AJAX with jQuery         

$.ajax method supports JavaScript Promises as well. 

.done() as replacement for .success()

.fail() as replacement for .error()

.always() as replacement for .complete()

$.ajax({
       data: someData,
       dataType: 'json',
       url: '/path/to/script'
}).done(function(data) {
      // If successful
      console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
      // If fail
      console.log(textStatus + ': ' + errorThrown);
});

Chaining Works

Assign the $.ajax() method to a variable, for which we can chain promise callbacks to. In this example, the $.ajax() method returns a promise object natively, which we can use chaining too:

var ajaxCall = $.ajax({
   context: $(element),
   data: someData,
   dataType: 'json',
   url: '/path/to/script'
});

ajaxCall.done(function(data) {
    console.log(data);
});

Multiple AJAX calls

We can compound several AJAX calls with their status $.when().

var a1 = $.ajax({...}),
a2 = $.ajax({...});

$.when(a1, a2).done(function(r1, r2) {
  console.log(r1[0]);
  console.log(r2[0]);
});

Dependence chain of AJAX requests

We can also chain multiple AJAX request. For example, when the second AJAX call relies on returned data on the first call. 

var a1 = $.ajax({
             url: '/path/to/file',
             dataType: 'json'
         }),

    a2 = a1.then(function(data) {
    // .then() returns a new promise
           return $.ajax({
              url: '/path/to/another/file',
              dataType: 'json',
              data: data.sessionID
             });
         });

a2.done(function(data) {
    console.log(data);
});

By Ami



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム