jQuery ajax error function

JqueryAjax

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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");
    });

Hope it helps!

Solution 2 - Jquery

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}

Solution 3 - Jquery

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.');
                  }
              }

Solution 4 - Jquery

error(jqXHR, textStatus, errorThrown)

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

Solution 5 - Jquery

          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);
          }

Solution 6 - Jquery

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
});

Solution 7 - Jquery

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);
    }
});

Solution 8 - Jquery

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()

Solution 9 - Jquery

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");
    }
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarryl WilsonView Question on Stackoverflow
Solution 1 - JquerypalaѕнView Answer on Stackoverflow
Solution 2 - JqueryczeraszView Answer on Stackoverflow
Solution 3 - JqueryRich CView Answer on Stackoverflow
Solution 4 - JqueryPraveen PrasadView Answer on Stackoverflow
Solution 5 - JquerysT0n3View Answer on Stackoverflow
Solution 6 - JqueryincreddibellyView Answer on Stackoverflow
Solution 7 - JqueryPouriaDieselView Answer on Stackoverflow
Solution 8 - JqueryJohn KloianView Answer on Stackoverflow
Solution 9 - JqueryPri NceView Answer on Stackoverflow