0

I have json object

{"errorType":"ValidationError","message":null,"errors":[{"message":"may not be empty"},{"message":"may not be empty"},{"message":"may not be empty"}]}

at the ajax error call back function.

function makeAjaxCall(){
    var send =serializeObject($("#employee"));
    send = JSON.stringify(send); 
    $.ajax({
        url: '/RestFul-Employee/addEmployee',
        type: 'POST',
        dataType: "json",       // Accepts
        data:send, 
        contentType : "application/json",
        success: function(result) {
            alert("success");
        },

        error: function(error){ 
         //so form validation error in form     

        }
    });
}

I need parse all form error message and show them in a form. I can not parse the error messages. Could you please help me?

Minderov
  • 521
  • 1
  • 5
  • 20
sanjeev bhusal
  • 245
  • 1
  • 14
  • 2
    What exactly are you having trouble with? – Jasen Aug 22 '16 at 23:33
  • I was parsing this "errors":[{"message":"may not be empty"},{"message":"may not be empty"},{"message":"may not be empty"}, section for all messages. messages are same but, i need to loop through all these messages to show in a form – sanjeev bhusal Aug 22 '16 at 23:34
  • You are probably looking for a way to iterate through an object. Take a look at this question: http://stackoverflow.com/questions/921789/how-to-loop-through-javascript-object-literal-with-objects-as-members – Minderov Aug 22 '16 at 23:36
  • Sorry is not more simple before to validate the form and than make the ajax call ? – Daebak Aug 22 '16 at 23:37

1 Answers1

0

{ "errorType": "ValidationError", "message": null, "errors":[ {"message":"may not be empty"}, {"message":"may not be empty"}, {"message":"may not be empty"} ] }

If you want to access the array of messages associated with the "errors" key, you can use the .length property to loop over the array and add elements to an error message array using the .push() method.

var errorMessages = [];
for(var i=0; i<errorJSON.errors.length; i++){
    if( errorJSON.errors[i].message != null ){
        errorMessages.push(errorJSON.errors[i].message;
    }   
}

Then you can associate the indices of the errorMessages with your form.

Jinw
  • 428
  • 5
  • 10