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
How to iterate over a JavaScript object?
or
You can use
Object.entries
to get the field and errors fromdata.errors
and then iterate each of those values: