0

I want to show the error message i get from controller in ajax error. So in my ajax error i have:

error: Function(e){
  Errordiv.empty();
  Errordiv.show();
  Errordiv.append(e.responseText);
  $.each(e.responseJSON.fieldErrors, function(i, v) {
    Errordiv.append(v.message);
    Errordiv.append("<br>");
  });
}

The problem is i get both of them. I don't want this. I want if there is any field error, no other message be displayed and if there is not then the error that controller sends be shown. I put a condition if

if(e.responseJSON.fieldErrors==null){...}

Then show other message and so on but it didn't work. How to solve it?

NOTE: Example message come from controller is "you have voted before!".

Update: fieldErrors are the validation messages of entity class. If the fields are not valid then the errors will be shown in Errordiv. And if all fields are ok but the user has voted before, the controller will send a message that will be shown by "Errordiv.append(e.responseText)". Now when there is a field error, the erros are shown twice. Once by the foreach loop and once by "Errordiv.append(e.responseText)". But when fields are valid it is ok and the errordiv contains only the message.

  • 1
    It's not clear what the problem is. What do you mean by 'the problem is I get both of them'. What is 'them'? What is the content of `e.responseJSON.fieldErrors`, and what output are you trying to create from it? – Rory McCrossan Aug 14 '19 at 08:03
  • What does the error object `e` looks like. Please can you update that in the question itself.And what do you mean by **The problem is i get both of them** – ambianBeing Aug 14 '19 at 08:04
  • I have edited the question – user11119835 Aug 14 '19 at 08:49
  • try to check if (e.responseJSON) before using it, otherwise use e.responseText. This https://stackoverflow.com/questions/3741574/jquery-how-to-check-response-type-for-ajax-call could help – Lety Aug 14 '19 at 09:27

1 Answers1

1

I solved it by changing the code to this:

Errordiv.empty(); 
Errordiv.show(); 
Errordiv.append(e.responseText); 
If(e.responseJSON.fieldErrors.length>0){
Errordiv.empty();
$.each(e.responseJSON.fieldErrors, function(i, v) { 
Errordiv.append(v.message); 
Errordiv.append("<br>");
});
}
}
});
});