Lars
Lars

Reputation: 8458

Javascript scope issue, ajax

I want to submit a form using ajax, then add a "disabled" class if the ajax request succeeds.

$("body").on("click", ".my_form", function(e){
    submit_form(e, $(this));    
});

function submit_form(e, _this){
    e.preventDefault();
    $.ajax({
        type:"POST",
        url:"/controller/common/form_processing.php", 
        data: "my form data goes here",
        dataType: "json", 
        success:function (data, _this) {
            _this.parents(".my_form").addClass("disabled");
       });
});

In it's current form, the "disabled" class is not being added. However, if I move the line: _this.parents(".thumbsup").addClass("disabled"); outside of the ajax brackets, it does work. (but obviously in this case, "disabled" will be added regardless of whether the ajax call succeeds or fails. Can somebody explain how to get this working properly? Thanks

Upvotes: 0

Views: 28

Answers (1)

Musa
Musa

Reputation: 97672

Remove the _this parameter from your success callback, you are redefining _this over the original one which is the jQuery object passed to submit_form

success:function (data) {
    _this.parents(".my_form").addClass("disabled");
});

Upvotes: 1

Related Questions