.ajax json return on error

$.ajax({ type: 'POST', url: api_url+'client/'+client.id+'.json', data: { _method: 'delete', id: client.id }, success: function(data) { $('#delete-client').html('Success'); }, error: function(data) { $('#delete-client').css('color', 'red'); $('#delete-client').html('Error'); } }); 

In case of error: the jquery function will receive this json object with a state of the header 500

 {"errors":{"code":777,"message":"Method requested does not yet exist","data":[]}} 

however, if I use data.errors.message, the error is not displayed there. It shows a huge object with various events in the chromes developer block when I console.log returns the object using

Fixed

 var error = jQuery.parseJSON(jqXHR.responseText); $('#delete-client').html(error.errors.message); 
+6
source share
2 answers

add: dataType:"json" ...............

+1
source

Try reading the $.ajax documentation :

error(jqXHR, textStatus, errorThrown) - Function

The called function if the request is not completed. The function receives three arguments: jqXHR (in the jQuery 1.4.x object, XMLHttpRequest), a string describing the type of error that occurred, and an optional exception object if one occurred. Possible values ​​for the second argument (except for zero): timeout, error, abort, and parsererror. When an HTTP error occurs, errorThrown receives the text part of the HTTP status, such as "Not Found" or "Internal Server Error." Starting with jQuery 1.5, an error can take a set of functions. Each function will be in turn. Note. This handler is not called for cross-domain script and JSONP requests. This is an Ajax event.

Check the argument list. This is not your data. This is a jqXHR object.


By definition, if you successfully retrieved data from the server, you have succeeded , not errored . Data is data, whether it contains the string "error" or not.

You should still use the success callback, even if your data describes an error. Do not send the 500 heading.


 $.ajax({ type: 'POST', url: api_url+'client/'+client.id+'.json', data: { _method: 'delete', id: client.id }, success: function(data) { if(data.errors) { //Server not able to process the request } else { $('#delete-client').html('Success'); } }, error: function(data) { //AJAX request not completed $('#delete-client').css('color', 'red'); $('#delete-client').html('Error'); } }); 
-4
source

Source: https://habr.com/ru/post/899882/


All Articles