Get Http status code from ajax response using jquery

In my current spring project, when I submit a form to the server, the response is processed using 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 view is processed with 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 controller methods are driven 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 the response (which could be 1xx, 2xx, 3xx, 4xx or 5xx) in my jquery code and display the appropriate message according to that code.

In Network Monitor from the browser, I can see that the successful response already has HTTP code 201 implemented in the method; when an error occurs, the response should be 4xx or 5xx, depending on the exception thrown.

So I am wondering if anyone can give a hint on how to modify my jquery code and my COntrollerAdvice to accomplish this.

+3


source to share


3 answers


It looks like you are using a jQuery form plugin . If so, the third parameter of the callback function is an object xhr

, and you can get the HTTP status like this:

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

      



jsfiddle

+4


source


Like this:

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

      

eg.

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

      

xhr is short for XmlHttpRequest.

readyState: values: 1: loading, 2: loading, 3: interactive, 4: full



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

responseText: response from 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 when successful, always use:

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

      

Also, see this post about the successful vs. full vs. done-fail-always
jQuery ajax () with success, error and complete vs .done (), fail () and always ()

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

+2


source


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 method using jQuerys ajax

+2


source







All Articles