Orlando
Orlando

Reputation: 975

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 $(this) inside of your success as ive seen tutorials use it but when i attempt to use it it doesnt work... However if i use $(document) or some other method to get to the object i want it works fine... Any help would be greatly appreciated as i am quite new to jQuery! Thanks in advance! The code im playing with is as follows:

$(".markRead").click(function() {
    var cId = $(this).parents("div").parents("div").find("#cId").val();
    var field = "IsRead";

    $.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...
            $(this).find("img").attr("src", "images/read.png");
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.statusText);
            alert(thrownError);
        }
    });
});

Upvotes: 2

Views: 1953

Answers (1)

jfriend00
jfriend00

Reputation: 707786

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);
        }
    });
});

Upvotes: 3

Related Questions