1

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.

4
  • JSON.stringify converts 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. Commented Jul 27, 2018 at 22:17
  • I actually just output the string to see if the correct JSON data was being returned. As far as the return structure, I have the capability of assigning messages to specific fields (versus one list of all errors). But I cannot figure out how to parse the json object. Commented Jul 28, 2018 at 1:14
  • What errors are you getting? What are you trying? Commented Jul 28, 2018 at 1:16
  • I updated the question with my attempt at parsing the json into the respective errors. I believe I'm one level off on the json object. Commented Jul 28, 2018 at 13:25

1 Answer 1

1

OK, I solved this problem. I just didn't understand how to get to the nested object in json.

I just needed to point to the correct data in the parsed json object:

$(document).on "ajax:error", "form", (event, data, status, xhr) ->

errorList = JSON.parse data.responseText
for own key, value of errorList.error
  console.log "#{key} -> #{value}"

Thanks for the response jvillian!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.