[jQuery] jQuery.ajax(options), $.ajax Memo

Tadashi Shigeoka ·  Fri, September 27, 2013

I often forget the arguments for jQuery’s $.ajax method and the arguments to specify for success, error, complete, etc., so here’s a memo.

$.ajax up to jQuery 1.7

$.ajax({
  url: 'http://api.example.com/v1/posts',
  type: 'POST',
  dataType: 'HTML',
  data: {
    id: '123'
  },
  success: function(data, statusText, xhr){
    if (xhr.status === 200) {
      // Processing on success
    } else if (xhr.status === 302) {
      // Branch processing based on HTTP status code

      // Redirect on 302
      location.href = 'http://example.com/redirect';
    }
  },
  error: function(xhr, statusText, error) {
    // Error handling
  },
  complete: function(xhr, statusText){
    // Common processing
  }
});

$.ajax from jQuery 1.8 onwards

It seems success, error, complete have been changed to .done, .fail, .always.

I’ll update this sometime.


Reference Information

jQuery.ajax()のまとめ: 小粋空間

jQuery モダンAjaxな書き方を目指して 〜Deferredを使ったAJAX〜 - Hack Your Design!

jQuery.ajax(options) - jQuery 日本語リファレンス

jQuery.ajax() | jQuery API Documentation

That’s all from the Gemba.