简体   繁体   中英

Jquery Ajax callback not working calling success and failed

I am trying to set a button text to 'Email sent' on success or 'Emailed failed' on failure. I am using ajax to call a method in MVC.

The call to to MVC works fine, but my code calls setButtonSuccess and setButtonFailed even before the json is ran?

Here is my code:

$('input[type=button]').click(function () {
        bookingID = $(this).closest('tr').attr('id');

        sendEmail(bookingID, this);
    });

function sendEmail(id, thisContext) {
    var data = JSON.stringify({ 'id': id });

/*******
 This calls setButtonSuccess AND setButtonFailed which is wrong
 I want to execute only setButtonSuccess OR setButtonFailed  depending on     whether successful or not
*******/
    jsonPOST("~Booking/ResendEmail", data, setButtonSuccess(thisContext, "Email Sent"), setButtonFailed(thisContext, "Email Failed"),false);
};

function setButtonSuccess(thisContext, buttonValue) {
    $(thisContext).val(buttonValue);
    $(thisContext).addClass("btn btn-success");
};

function setButtonFailed(thisContext, buttonValue) {
    $(thisContext).val(buttonValue);
    $(thisContext).addClass("btn btn-warning");
};

function jsonPOST  (pWebServiceFunction, pData, pOnCallbackSuccess,    pOnCallbackFailed, async) {
    $.ajax({
        type: "POST",
        url: url + pWebServiceFunction,  
        data: pData,                     
        contentType: "application/raw; charset=utf-8",                                         dataType: "json",
        async:async,
        processdata: true,  
        success: function (msg) {
            if (msg.success === true) {
                pOnCallbackSuccess(msg);
            }
            else {
                pOnCallbackFailed(url + pWebServiceFunction);
            }
        },
        error: function (xhr, ajaxOptions, thrownError)       //When Service call fails
        {
            pOnCallbackFailed(url + pWebServiceFunction, pData, xhr.status, xhr.statusText, xhr.responseText);
        }
    });
};

Thanks

You're calling the functions immediately instead of passing a function that will call them later. It should be:

jsonPOST("~Booking/ResendEmail", data, function() {
    setButtonSuccess(thisContext, "Email Sent");
}, function() {
    setButtonFailed(thisContext, "Email Failed");
}, false);

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