I have an AJAX form to change password, I want to display all the validation errors in a HTML DIV.
Below is my code, it's working fine to submit the form, but I can't pass the errors to the DIV, I keep getting: [object Object]
.
var url = "/posts/editProfile"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#profileForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
},
error: function(data)
{
console.log(data);
$("#response").text(data);
}
});
e.preventDefault();
});
<div id="response"> <!-- output here --> </div>
This is because you are trying to set the inner text of a div element by simply passing the error object that's why you are getting [object Object] I'd suggest you examine your error object in debug mode, or by simply printing it as you did actually, and instead of doing
$("#response").text(data);
do something like
$("#response").text(data.responseJSON.responseText);
But that will simply dump some error text within the DIV, i guess you want to show some meaningful validation to your users, to achieve this simply use your error object to display proper data whichever way it suits you best.
this question is about more than three years, and until now no answer, I find it, but I'm sure you have found a solution to this problem. this easy way, my solution is:
error: function(error)
{
// this Error is an Object
var errors = error.responseJSON.errors;
// Loop this object and pring Key or value or both
for (const [key, value] of Object.entries(errors)) {
console.log(`${key}: ${value}`);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.