简体   繁体   中英

JQuery Ajax Type error in success callback

I create a button that when clickes do something with Ajax in server and when come back from server color of the button and its text will change (something like +1 add friend in facebook) here is my code in .js :

$(".blue").on("click", function(){
    var firstName = $(this).prev().prev().text();
    var lastName = $(this).prev().text();
    $(this).text("Add Friend...");
    var data={
        firstName: firstName,
        lastName: lastName
    };
    $.ajax({
        url: '/ajax/friendRequest',
        data: data,
        dataType: 'json',
        success:function(){
            alert(123);
            $(this).removeClass("glass blue");
            $(this).addClass("greenStatic");
            $(this).text("Request sent");
        }
    });
});

every thing is OK and request will successfully change the database but when it comeback to the success callback I only see the alert(123); on the browser and 3 below lines don't run and my chrome developer tools throw exception of typeError I search SO and change $ sign to jQuery but still I have same problem

In your success callback $(this) doesn't refer to the button, cache it outside of the success callback, like

$(".blue").on("click", function(){
    var btn = $(this);
    ...
    ....
    success:function(){
        ...
        btn.addClass("greenStatic");
        ...
    }
});
        $(this).removeClass("glass blue");
        $(this).addClass("greenStatic");
        $(this).text("Request sent");

Here this does not refer to the control, rather it refers to the Ajax request object. So, replace this by the control id. It should work.

Something like below...

        $("#controlId").removeClass("glass blue");
        $("#controlId").addClass("greenStatic");
        $("#controlId").text("Request sent");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM