83665

Get Http Status Code from an ajax response with jquery

Question:

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.

Answer1:

It looks like you are using the <a href="http://malsup.com/jquery/form/" rel="nofollow">jQuery Form Plugin</a>. 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);

<a href="http://jsfiddle.net/9tdmoc9s/" rel="nofollow">jsfiddle</a>

Answer2:

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<br /><a href="https://stackoverflow.com/questions/18264237/jquery-ajax-using-success-error-and-complete-vs-done-fail-and-always" rel="nofollow">jQuery ajax() using success, error and complete vs .done(), .fail() and always()</a>

If you want to setup a global error handling on the page, use ajaxSetup:<br /><a href="http://www.unseenrevolution.com/jquery-ajax-error-handling-function/" rel="nofollow">http://www.unseenrevolution.com/jquery-ajax-error-handling-function/</a>

Answer3:

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: <a href="http://osric.com/chris/accidental-developer/2014/08/using-getresponseheader-with-jquerys-ajax-method/" rel="nofollow">Using getResponseHeader with jQuery’s ajax method</a>

Recommend

  • Django url pattern multiple Parameters (without pk)
  • Snapshot test with Jest on nested react-navigation component - Object keys change so Snapshot match
  • Match everything except a specific pattern in JavaScript
  • How do I create a Builder that can build more than one kind of Java object?
  • Bootstrap 3 Nested Multi Carousel
  • How to use Tesseract.js in a React app
  • How to get each track of a playlist with the Soundcloud API?
  • Converting object to Int pandas
  • has_and_belongs_to_many relationship not associating both ways
  • Authorization Policies/Gates for Laravel 5.3 web app consuming own API w/ Passport
  • How do I hide and show the contents contents of a modal?
  • Using one probability set to generate another [duplicate]
  • Change selectOneMenu stylesheet (Primefaces)
  • nodeValue from DomDocument returning weird characters in PHP
  • Matlab - fixed text size when zooming
  • QNetworkAccessManager one instance and connecting slots
  • Python C binding error
  • DocuSign API Replace template document but keep fields
  • List using with references, changes behavior when used as a member
  • Implementing and using MinMax with four in row (connect4) game
  • Corda: How to implement hierarchical relationships between state data persisted to H2
  • yii rewrite url with many sub categories
  • characters not allowed in DOM ids by spec, and by browser
  • Can't hide status bar in AVPlayerViewController's portrait mode
  • Scheme procedure to compute the nth repeated application of a function?
  • Bison does not appear to recognize C string literals appropriately
  • Extracting a small subset of data from XMLs
  • Windows biometric framework sample umdf driver: This device cannot start. (Code 10)
  • How to make Rss News Reader application in android …? [closed]
  • Java .policy file - how to prevent java.util.Date() from being accessible
  • using maven pom while creating jar:test-jar some times it says JAR will be empty - no content was ma
  • Stacked bar chart with continuous time-axis as x-axis
  • How do I add a mouse over tooltip to an Image using .DrawImage()
  • Google App Engine Datastore: Dealing with eventual consistency
  • read part of h5 dataset python
  • ssh remote server login script
  • How to call different template for different category archive page in woocommerce
  • Write to .csv file with PHP (Commas in Data Error)
  • ARKit code issue {unknown error -1=ffffffffffffffff error: Task failed with exit 1}