Colin Steel
Colin Steel

Reputation: 1055

Call ajax.fail() from ajax.success()

So all I want to do is conditionally call the .fail method from within the .success method, how?

var ajaxCall = $.ajax({
    url: pUrl,
    type: "POST",
    data: pData,
    dataType: "json",
    processData: false,
    contentType: "application/json; charset=utf-8"
})
.always(function () {
    alert("always");
})
.success(function (data) {
    if (data == "fail") { ajaxCall.fail(); return; }
    alert("success");
})
.fail(function () {
    alert("fail");
});

Upvotes: 0

Views: 85

Answers (3)

D.T.
D.T.

Reputation: 350

just use the "this" keyword to actually call any other method of the ajax call, I have made a sample for error method.

$.ajax({
                    url: 'url',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8;',
                    type: 'GET',
                    success: function (dataReturn) {
                        this.error('error called explicitly');
                    },
                    error: function (errorMessage) { 
                        if(errorMessage.ResponseText) // or directly compare as errorMessage !== "error called explicitly" if u send the same message elsewhere
                            //actual error code
                        else
                            alert(errorMessage); 
                    }
                });

hope this helps :)

Upvotes: 0

Neel
Neel

Reputation: 11721

You can simply call as this.fail(); as shown below :-

var ajaxCall = $.ajax({
    url: pUrl,
    type: "POST",
    data: pData,
    dataType: "json",
    processData: false,
    contentType: "application/json; charset=utf-8"
})
.always(function () {
    alert("always");
})
.success(function (data) {
    if (data == "fail") 
    { 
        this.fail();
        return; 
    }
    alert("success");
})
.fail(function () {
    alert("fail");
});

For more information :-

http://www.youlikeprogramming.com/2013/07/jqueryajax-conditionally-call-error-method-fro-success/

Upvotes: 0

Magus
Magus

Reputation: 15104

$.ajax return a promise so you can't do it directly. Your best shot is that :

var fail = function () {
    alert("fail");
};

var ajaxCall = $.ajax({
    url: pUrl,
    type: "POST",
    data: pData,
    dataType: "json",
    processData: false,
    contentType: "application/json; charset=utf-8"
})
.always(function () {
    alert("always");
})
.success(function (data) {
    if (data == "fail") { fail(); return; }
    alert("success");
})
.fail(fail);

Upvotes: 2

Related Questions