0

Am using AJAX code whereby I handle errors form the backend code.. All is working well except that I want to alert the errors individually to the user in a numbered list

Expected Output

1. Please insert a valid phone number
2. Please insert your email
3. Please insert a valid passport number 

AJAX code handling errors

error: function(data) {
                //Unblock the spinner
                $.unblockUI();
                var errors = '';
                for(datos in data.responseJSON){
                    errors += data.responseJSON[datos] + '<br>';
                }
                //Alert each error individually
                alert(errors);
            }
Patweb
  • 133
  • 1
  • 10

2 Answers2

0

It is not clear to me from the question, whether you want a

  1. multiline alert message or

  2. multiple alert dialogs as the output,

but in case 1) is true, you should use newline ("\n") instead of br tag - see New line in JavaScript alert box and the code could look like:

var i = 1,
    errors = '';

for(datos in data.responseJSON){
    errors += i + '. ' + data.responseJSON[datos] + '\n';
    i++;
}

//Alert each error individually
alert(errors);

If 2) is what you need, you should call alert() for each error message

James Wrcsti
  • 220
  • 1
  • 8
0

I would recommended that you should be using a for loop instead of for in. See why here

error: function(data) {
  //Unblock the spinner
  $.unblockUI();
  var errors = '';
  for(var i = 0; i < data.responseJSON.length; i++){
    // Remove the "(i+1) + '. ' + " if your json response already contains that part.
    errors += (i+1) + '. ' + data.responseJSON[i] + '\n'; // <-- Notice how the br tag is changed to a new line
  }
  alert(errors)
}

I also changed the <br> tag to a \n as alerts don't support html tags.

dasmikko
  • 696
  • 2
  • 8
  • 29