Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Http Status Code from an ajax response with jquery

In my current spring project, when I submit a form to server, the response is handled by this method:

    $('form.form').each(function () {
        var form = this;
        $(form).ajaxForm(function (data) {
            form.reset();
            $(".alert-info").find("#alert").html(data);
            $(".alert-info").show();
        });
    });

In my controller, the submission is handled by a method like this:

@RequestMapping(value="cadastra", method=RequestMethod.POST)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public void cadastra(@ModelAttribute("object") E object, BindingResult result, @RequestParam(value="file", required=false) MultipartFile file, @RequestParam(value="icone", required=false) MultipartFile icone, @RequestParam(value="screenshot", required=false) MultipartFile screenshot[]) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
    serv.cadastra(object);
    serv.upload_picture(object, file, "picture");
    serv.upload_picture(object, icone, "icone");
}

Error responses from the methods from the controller are handled by this ControllerAdvice class:

@ControllerAdvice
@PropertySource({"classpath:error.properties"})
public class GlobalDefaultExceptionHandler {

    @Autowired
    private Environment env;

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        // If the exception is annotated with @ResponseStatus rethrow it and let
        // the framework handle it - like the OrderNotFoundException example
        // at the start of this post.
        // AnnotationUtils is a Spring Framework utility class.
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;
        // Otherwise setup and send the user to a default error-view.
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.addObject("msg", e.getLocalizedMessage());
        mav.setViewName("erro");
        return mav;
    }

}

I am looking for a way to read the http status code from response (which can be 1xx, 2xx, 3xx, 4xx or 5xx) in my jquery code, and display a related message according to this code.

In the network monitor from browser, I can see a successful response already have the code HTTP 201 as implemented in the method; when an error occurs, the response should have a code 4xx or 5xx, depending from exception triggered.

In this way, I wonder if anyone can give a hint of how modify my jquery code and my COntrollerAdvice to accomplish this.

like image 414
Kleber Mota Avatar asked Aug 23 '14 23:08

Kleber Mota


3 Answers

It looks like you are using the jQuery Form Plugin. If so, the third parameter to the callback function is the xhr object, and you can get the HTTP status like this:

$(form).ajaxForm(function (data, statusText, xhr) {
    alert(xhr.status);

jsfiddle

like image 52
John S Avatar answered Sep 29 '22 20:09

John S


Like this:

$.ajax({
    type: "post", url: "/SomeController/SomeAction",
    success: function (data, text) {
        //...
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

e.g.

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

xhr is short for XmlHttpRequest.

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

status: the HTTP status number, like 404 not found, 500 internal server error, 200: ok (warning: special IE problem value: 0 cancelled)

responseText: the response from the server - this could be your custom status text (make sure the status code is not 200 OK)

If you want to check the status even on success, use always:

var jqxhr = $.ajax( "example.php" )
.done(function (data) { alert(data); })
.fail(function (jqXHR, textStatus, errorThrown) { someErrorFunction(); })
.always(function() { alert("complete"); });

Also, see this post on success-error-complete vs. done-fail-always
jQuery ajax() using success, error and complete vs .done(), .fail() and always()

If you want to setup a global error handling on the page, use ajaxSetup:
http://www.unseenrevolution.com/jquery-ajax-error-handling-function/

like image 23
Stefan Steiger Avatar answered Sep 29 '22 19:09

Stefan Steiger


To get headers and status in response:

$.ajax({
    dataType: "json",
    url: url,
    data: data
}).done(function(rs, textStatus, xhr) {
    console.log(xhr.getResponseHeader('X-CUSTOM-HEADER'));
    console.log(xhr.status);
});

see also: Using getResponseHeader with jQuery’s ajax method

like image 36
aGuegu Avatar answered Sep 29 '22 19:09

aGuegu