Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show proper error messages with jQuery AJAX

Tags:

jquery

Currently if I have an error with an ajax request such as submitting a form (I'm using ASP.NET MVC 3) it will show something like 'Internal Server Error'.

But if I do the submit without using Ajax then .net will show the actual server error.

Any ideas on how I could perhaps get the error to show? So my users can report the problem instead of only being able to say 'internal server error'

Thanks

like image 540
Cameron Avatar asked Nov 07 '11 18:11

Cameron


People also ask

What is processData in AJAX?

processData: It's default value is true. It is used to specify whether or not data sent with the request should be transformed into a query string.

What is AJAX error function?

The ajaxError() method in jQuery is used to specify function to be run when an AJAX request fails. Syntax: $(document).ajaxError( function(event, xhr, options, exc) ) Parameter:: This method accepts single parameter function which is mandatory.

What is jqXHR in AJAX?

The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.


2 Answers

Although I wouldnt recommend showing the user an error number with the actual response error message this is how you can do this by adding the error callback

error: function(xhr,err){
    alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
    alert("responseText: "+xhr.responseText);
}

xhr is XmlHttpRequest.

readyState values are 1:loading, 2:loaded, 3:interactive, 4:complete.

status is the HTTP status number, i.e. 404: not found, 500: server error, 200: ok.

responseText is the response from the server - this could be text or JSON from the web service, or HTML from the web server.

like image 147
Manse Avatar answered Oct 13 '22 06:10

Manse


This code will replace the current page's contents with the error that came back from the ajax request.

jQuery(document).ajaxError(function (event, request, settings) {
    if (request.status === 500) {
        $(document.body).html(request.responseText);
    } else if (request.status === 401) {
        // redirect to login, 401 means session is expired.
        window.location.href = "login page url";
    }
});
like image 37
BNL Avatar answered Oct 13 '22 07:10

BNL