Preserving Context of this Inside AJAX Response Callbacks in jQuery

javascript
Published on November 29, 2019

Use-Cases of this video information

  • Know how to access "this" inside jQuery AJAX success and error callbacks.
  • Know how to set a context for AJAX callback functions.
  • Know how to use $.proxy() method for AJAX callbacks.
  • Know how to access global scope inside AJAX callbacks using globalThis property.

"this" can be accessed inside jQuery AJAX success and error callbacks by setting the "context" configuration property for $.ajax() or changing context of AJAX callbacks using $.proxy() method.

It is very common to access this inside jQuery AJAX's response callbacks (success or error). This tutorial describes 3 ways of doing this.

Method 1 — Using the context Configuration Property

While using $.ajax(), the context property can be included. This sets the context of the AJAX callbacks.

The value of this property can be set as this (or any other context that we'd want).

$("#button_that_initiated").on("click", function() {
    $.ajax({
        url: "fetch-list.php",
        context: this, 
        type: "GET",
        dataType: "JSON",
        success: function(response) {
            // "this" would refer to $("#button_that_initiated")
        }
    });
});

Method 2 — Using $.proxy() Method

$.proxy() can set the context of any function or callback. This can be used in success and error callbacks to set their context.

$.ajax({
    url: "api.php",
    type: "GET",
    dataType: "JSON",
    success: $.proxy(function(response) {
        // "this" refers to "this" parameter passed to $.proxy()
    }, this),
    error: $.proxy(function(response) {
        // "this" refers to "this" parameter passed to $.proxy()
    }, this)
});

Method 3 — Using globalThis to Access Global Scope

globalThis is a new property recently added to browsers. This refers to the global level "this".

If we need to access functions / variables defined in global scope inside $.ajax() response callbacks, we can use globalThis.

$.ajax({
    url: "api.php",
    type: "GET",
    dataType: "JSON",
    success: function(response) {
        // "showResponse" is a global function
        globalThis.showResponse(response);
    }
});
In this Tutorial