Home > Software engineering >  How do I handle a JQuery/AJAX error response?
How do I handle a JQuery/AJAX error response?

Time:01-20

Probably it is very simple but I can't figure out how to handle the jQuery/AJAX error

I've managed to submit a form with AJAX, it works perfectly except I can't catch and display the error(s) as I would like.

The response is under the form of JsonResponse and returns this array with all the errors (can be one or multiple) {error: {account_number: ["Account with this Account number already exists."]}}

I would like to display in a div all the errors but the following code doesn't work

$("#form").submit(function(e) {
  e.preventDefault();
  // serialize the data for sending the form data.
  var serializedData = $(this).serialize();
  // make POST ajax call
  $.ajax({
    type: 'POST',
    url: "ajax_call.php",
    data: serializedData,
    success: function(response) {
      alert('Done!')
    },
    error: function(response) {
      // alert the error if any error occured
      $("#error-message").prepend(
        response["responseJSON"]["error"]
      )
    }
  })
})

CodePudding user response:

I have found the problem, I wasn't handling the response correctly

error: function (response) {
  var error = response ["responseJSON"]["error"];
  $.each(error, function( code, message ) {
     $('#error-message').show().append(message);
  });
}
  •  Tags:  
  • Related