skip to Main Content

I have server-side validation in PHP that returns an array which I convert to JSON which is retrieved via vanilla JS fetch.

...
echo json_encode($response);
exit;

which sends:

{"status":"error","html":"
<p class='error'>
    There are errors, please check over the form.</p>","errors":{"title":["This field was empty. ", "There are formatting errors also"]}}

… back to the javascript and handled:

fetch(the_form.getAttribute('action'), { method: $method, headers: {"X-Requested-With": "XMLHttpRequest"}, body: new FormData(the_form) })
            .then(response => response.json())
            .then(function (data) {
            if (data.status == "success") {
                 // DO SUCCESS STUFF
            } else {
                 display_validation_errors(data.errors);
            }
}

I’m then passing the data.errors through to the function display_validation_errors().

It is here where I am unsure how to loop through the data.errors passed into that function.

The data.errors is itself an array of form field names, each containing an array of error messages about that field. There are no keys on that inner array.

How to I loop through both the field names (eg: "title" in this example output), and then the key-less error messages inside it. This is the function I have in JS and it’s putting out errors:

function show_validation_errors(errors) {

    // LOOP THROUG ARRAY
    for (let error of errors) {
        console.log(the field name here);
        for (let the_error of error) {
           console.log(the error message here);
        }
    }

}

I know I’m missing something crucial with the handling of the object being passed into the function to then loop through it.

FYI, everything else is working. I Can access the data.status with no issue, same for data.html. It’s the nested nodes I am having issues looping through.

Thanks in advance!

2

Answers


  1. How to iterate over a JavaScript object?

    const data = {
      "status": "error",
      "html": "<p class='error'>There are errors, please check over the form.</p>",
      "errors": {
        "title": ["This field was empty. ", "There are formatting errors also"]
      }
    }
    
    show_validation_errors(data.errors)
    
    function show_validation_errors(errors) {
      for (const key in errors) {
        console.log('key', key);
        for (const the_error of errors[key]) {
          console.log('message', the_error);
        }
      }
    
    }

    or

    const data = {
      "status": "error",
      "html": "<p class='error'>There are errors, please check over the form.</p>",
      "errors": {
        "title": ["This field was empty. ", "There are formatting errors also"]
      }
    }
    
    show_validation_errors(data.errors)
    
    function show_validation_errors(errors) {
      for (const [key, array] of Object.entries(errors)) {
        console.log('key', key);
        for (const the_error of array) {
          console.log('message', the_error);
        }
      }
    
    }
    Login or Signup to reply.
  2. You can use Object.entries to get the field and errors from data.errors and then iterate each of those values:

    const data = {
      "status": "error",
      "html": "<p class='error'>    There are errors, please check over the form.</p>",
      "errors": {
        "title": ["This field was empty. ", "There are formatting errors also"]
      }
    }
    
    function show_validation_errors(errors) {
        // LOOP THROUGH ARRAY
        Object.entries(errors).forEach(([field, errs]) => {
            console.log(field);
            errs.forEach(e => console.log(e));
        })
    }
    
    show_validation_errors(data.errors)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search