Jquery Ajax Success Doesn't Work With $(this)?
Ive been playing with the ajax tools in jQuery and am having an issue with using $(this) inside the success of the execution of my ajax. I was wondering if its possible to use $(th
Solution 1:
this
always refers to the current execution context so it does not necessarily stay the same in a callback function like an ajax success handler. If you want to reference it, you must just do as Dennis has pointed out and save its value into your own local variable so you can reference it later, even when the actual this
value may have been set to something else. This is definitely one of javascript's nuances. Change your code to this:
$(".markRead").click(function() {
var cId = $(this).parents("div").parents("div").find("#cId").val();
var field = "IsRead";
var element = this; // save for later use in callback
$.ajax({
type: "POST",
url: "ajax/contract_buttons.php",
dataType: "text",
data: "contractId=" + cId + "&updateField=" + field,
async: false,
success: function(response) {
//$(this) doesnt recognize the calling object when in the success function...
$(element).find("img").attr("src", "images/read.png");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(thrownError);
}
});
});
Post a Comment for "Jquery Ajax Success Doesn't Work With $(this)?"