161

I have an ajax call passing data to a page which then returns a value.

I have retrieved the successful call from the page but i have coded it so that it raises an error in the asp. How do i retrieve that error from the jquery?

For example:

cache: false,
url: "addInterview_Code.asp",
type: "POST",
datatype: "text",
data: strData,
success: function (html) {
    alert('successful : ' + html);
    $("#result").html("Successful");
},
error: function (error) {
    **alert('error; ' + eval(error));**
}

It's the error bit that I don't understand. In the function what parameter do I need to put, so that I can then use the error message that I raised in the server.

4
  • 1
    There's a typo there: it's dataType not datatype. Commented Dec 24, 2016 at 22:49
  • 1
    Also, jQuery says you can't use both success and error, just like you did. Commented Dec 24, 2016 at 22:52
  • 7
    @alej27: the wording is kind of odd, but it doesn't say you can't use them both, it says a request will not call success and error (because they're mutually exclusive). Commented Aug 7, 2017 at 21:24
  • Use care with answers here As of jQuery 3.0 the deprecated noted on .error and .success become more important as they have been removed. Commented Jun 4, 2020 at 17:00

9 Answers 9

287

The required parameters in an Ajax error function are jqXHR, exception and you can use it like below:

$.ajax({
    url: 'some_unknown_page.html',
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});

DEMO FIDDLE


Parameters

jqXHR:

Its actually an error object which is looks like this

Ajax error jqXHR object

You can also view this in your own browser console, by using console.log inside the error function like:

error: function (jqXHR, exception) {
    console.log(jqXHR);
    // Your error handling logic here..
}

We are using the status property from this object to get the error code, like if we get status = 404 this means that requested page could not be found. It doesn't exists at all. Based on that status code we can redirect users to login page or whatever our business logic requires.

exception:

This is string variable which shows the exception type. So, if we are getting 404 error, exception text would be simply 'error'. Similarly, we might get 'timeout', 'abort' as other exception texts.


Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

So, in case you are using jQuery 1.8 or above we will need to update the success and error function logic like:-

// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax("some_unknown_page.html")
    .done(function (response) {
        // success logic here
        $('#post').html(response.responseText);
    })
    .fail(function (jqXHR, exception) {
        // Our error logic here
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    })
    .always(function () {
        alert("complete");
    });
Sign up to request clarification or add additional context in comments.

3 Comments

Interestingly it is not recommended to use ajaxSetup. See api.jquery.com/jquery.ajaxsetup
@palaѕн I think you misread the deprecation notice. If you notice, the deprecation notice is talking about a deprecation of methods of jqXHR, but the use of success, error and complete in your above example are done within an object to the $.ajax method. This has not been deprecated and you don't need to switch your code. However, if one prefers to chain the methods then you could use this style. When I read "deprecation..." this threw me off (for no reason). :-)
As of jQuery 3.0 the deprecated noted on .error and .success become more important as they have been removed
109

Try this:

error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
}

If you want to inform your frontend about a validation error, try to return json:

dataType: 'json',
success: function(data, textStatus, jqXHR) {
   console.log(data.error);
}

Your asp script schould return:

{"error": true}

1 Comment

What is textSttaus and errorThrown is for? Can you please explain
5

Here is how you pull the asp error out.

              cache: false,
              url: "addInterview_Code.asp",
              type: "POST",
              datatype: "text",
              data: strData,
              success: function (html) {
                  alert('successful : ' + html);
                  $("#result").html("Successful");
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  if (jqXHR.status == 500) {
                      alert('Internal error: ' + jqXHR.responseText);
                  } else {
                      alert('Unexpected error.');
                  }
              }

Comments

2
error(jqXHR, textStatus, errorThrown)

http://api.jquery.com/jQuery.ajax/

2 Comments

Please provide some explanaition, not just a piece of code and a link do docs.
for instance, you could've said "OP is using a function error(error) but jquery is calling a function error(jqXHR, textStatus, errorThrown). Notice the 2 missing parameters in OP's snippet."
2
          cache: false,
          url: "addInterview_Code.asp",
          type: "POST",
          datatype: "text",
          data: strData,
          success: function (html) {
              alert('successful : ' + html);
              $("#result").html("Successful");
          },
          error: function(data, errorThrown)
          {
              alert('request failed :'+errorThrown);
          }

Comments

2

you're using a function

error(error) 

but jquery is actually looking for a function with three parameters:

error(jqXHR, textStatus, errorThrown)

you'll need to add two more parameters.

ALSO: please have a look at all the comments above that mention 'deprecated' :)

$.ajax("www.stackoverflow.com/api/whatever", {
    dataType:"JSON"
    data: { id=1, name='example' }
}).succes(function (result) {
    // use result
}).error(function (jqXHR, textStatus, errorThrown) {
    // handle error
});

4 Comments

you'll need to add two more parameters - this is so wrong.
hmm. if that's all you have to say - maybe not say anything? or, you COULD explain your statement and actually help. Your choice.
In JavaScript, say you have a method - function myMethod (err) { alert(err); } and then call it like myMethod ("something is wrong", 500, some_object) - This will work without any issue. As per your statement, this would only work if the method signature is function myMethod (err, status, some_object). Forget about the above example, the signature of the success event you have in the answer is actually .success(data, status, xhr), but if you just need the result, we usually bind it like .success (data) and both works.
And what value add did you bring by adding this answer? IMO there isn't any info in your answer which was missing in the previous answers. Only thing you did was pulling this question up in the stack again.
2

You can use something like this:
note: responseText returns server response and statusText returns the predefined
message for status error.for e.g:
responseText returns something like "Not Found (#404)" in some frameworks like Yii2 but
statusText returns "Not Found".

$.ajax({
    cache: false,
    url: "addInterview_Code.asp",
    type: "POST",
    datatype: "text",
    data: strData,
    success: function (html) {
        alert('successful : ' + html);
        $("#result").html("Successful");
    },
    error: function (data) {
        console.log(data.status + ':' + data.statusText,data.responseText);
    }
});

Comments

0

From jquery.com:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callback methods introduced injQuery 1.5 are deprecated
as of jQuery 1.8. To prepare your code for their eventual 
removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you want global handlers you can use:

.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(),
.ajaxSuccess(), .ajaxSend()

Comments

0

This works for me.

$.ajax({
    type: 'POST',
    url: url,
    data: {
        menu: str
    },
    beforeSend: function(){
        $.notify("sorting", "info");
    },
    success: function(data) {
        $.notify("success", "success");
    },
    error: function (data) {
        $.notify("Opps!", "error");
    }
    });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.