$(this) inside of AJAX success not working

Problem

Inside the callback, this refers to the jqXHR object of the Ajax call, not the element the event handler was bound to. Learn more about how this works in JavaScript.


Solutions

If ES2015+ is available to you, then using an arrow function would probably be the simplest option:

$.ajax({
    //...
    success: (json) => {
         // `this` refers to whatever `this` refers to outside the function
    }
});

You can set the context option:

This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). (...)

$.ajax({
    //...
    context: this,
    success: function(json) {
         // `this` refers to the value of `context`
    }
});

or use $.proxy:

$.ajax({
    //...
    success: $.proxy(function(json) {
         // `this` refers to the second argument of `$.proxy`
    }, this)
});

or keep a reference to the value of this outside the callback:

var element = this;

$.ajax({
    //...
    success: function(json) {
         // `this` refers to the jQXHR object
         // use `element` to refer to the DOM element
         // or `$(element)` to refer to the jQuery object
    }
});

Related

  • How to access the correct `this` inside a callback?

Tags:

Jquery