How to pass $(this) in success callback of $.ajax How to pass $(this) in success callback of $.ajax ajax ajax

How to pass $(this) in success callback of $.ajax


$(this) is relative to the inner-most function, and in this case you'll need to assign $(this) to a variable before the ajax query, and use that variable in the success instead.

$("#tb1").focusout(function(){    var elem = $(this);    $.ajax({        type:'POST',        url: 'validURL',        data: {various_parameters},        contentType: 'application/json; charset=utf-8',        dataType:'json',        success: function(data){            validInput(data, elem);        },        error: error    });}


Well that is because context of focusout element is lost in ajax call.

You can set context option in ajax to reference of DOM object for setting context in ajax to element context:

$("#tb2").focusout(function(){  $.ajax({    type:'POST',    url: 'validURL',    context : this,    data: {various_parameters},    contentType: 'application/json; charset=utf-8',    dataType:'json',    success: function(data){        validInput(data, $(this));    },    error: error  });});


Alternative way you can achieve this is by referencing it in the first place.

$("#tb2").focusout(function(){    var $this = $(this);    $.ajax({        type:'POST',        url: 'validURL',        data: {various_parameters},        contentType: 'application/json; charset=utf-8',        dataType:'json',        success: function(data){            validInput(data, $this);        },        error: error    });}