I have a contact form through which users would be able to contact me. I am using django with ajax, and it works fine if there\'s no error. I would like to show
as an example
django form returns errors with json format using form.errors.as_json(). assume:
{
"sender": [
{
"message": "Enter a valid email address.",
"code": "invalid"
}
],
"subject": [
{
"message": "This field is required.",
"code": "required"
}
]
}
after that, ajax get a response (in success: function(data) {}
. assume already become an object:
data = {
"sender": [
{
"message": "Enter a valid email address.",
"code": "invalid"
},
{
"message": "Enter a .",
"code": "invalid"
}
],
"subject": [
{
"message": "This field is required.",
"code": "required"
}
]
};
and you're already renders previous form, assume:
and to render these messages, you can write scripts in the click events:
// in ajax success (event click)
if ($("input").next('p').length) $("input").nextAll('p').empty();
for (var name in data) {
for (var i in data[name]) {
// object message error django
var $input = $("input[name='"+ name +"']");
$input.after("" + data[name][i].message + "
");
}
}
simulation example:
// simulation example, Data obtained from ajax response
var data = {
"sender": [
{
"message": "Enter a valid email address.",
"code": "invalid"
},
{
"message": "Enter a .",
"code": "invalid"
}
],
"subject": [
{
"message": "This field is required.",
"code": "required"
}
]
};
$("button").on("click", function() {
if ($("input").next('p').length) $("input").nextAll('p').empty();
for (var name in data) {
for (var i in data[name]) {
// object message error django
var $input = $("input[name='"+ name +"']");
$input.after("" + data[name][i].message + "
");
}
}
});