I'm trying to parse out validation error messages returned from a Ruby model on the client side, but I am running into problems.
The application returns errors in JSON as expected:
"{"error":{"first_name":["can't be blank"],"last_name":["can't be blank"]}}"
I cannot figure out how to parse the errors out of the JSON. I would like to parse out each component pair...i.e. get the field (first_name) and error message ("can't be blank"), but I keep running into errors.
How can i parse these individual pieces out of the response? I suppose i lack understanding of how to parse the json string into each of its respective components.
I've included the relevant ajax:error function below. I appreciate any help! Thank you!
$ ->
$(document).on "ajax:error", "form", (evt, data, status, xhr) ->
list_area = $('#error-explanation ul')
list_area.empty()
for own key, value of errorList
console.log "#{key} -> #{value}"
The code above outputs to the console:
error -> [object Object]
I was expecting to see first_name -> can't be blank. I believe I am not parsing the object correctly.
JSON.stringifyconverts a JavaScript value to a JSON string. I don't think you want to be doing that. Your data should be (I think) a js object that you can work with directly. BTW, it might be easier/nicer to send back rendered errors html and append that.