I have a modal dialog where I load a form from a gsp and I am struggling to find the right solution for an ajax based form with JSON validation incl. success message like a flash scope message:
$('#calendar_form').live('click', function () {
$.modal({
ajax: './form'
, title: '${message(code:'calendar.main.addAppointment')}'
, overlayClose: true
});
});
In that form I have the following JS:
$(document).ready(function() {
$('#form1').submit(function() {
$.ajax({
type: 'POST',
url: '${createLink(action:'post')}',
data: $("#form1").serialize(),
success: function(result) {
alert(result);
}
});
});
});
I am returning a JSON response if its successful and when an error occurs and I need Ajax otherwise my modal dialog is disapearing due to the new request.
So here are my questions:
- How do I react on failures which happen during my validation in my controller?
- Which error http codes do I need to use for validation errors in my controller?
- How do I update the specific fields with error messages in my form?
- How do I update the flash part of my page to render the success msg?
- How is it possible to update other parts of the page after success?
Thank you!
There are a lot of different ways to accomplish this and probably 1 or more plugins to get you going. However, I’ll show you how I generally deal with this. I have an object that looks like this…
This is the object I render as JSON. So if there are validation errors, success becomes false and I add all the errors to the errors map. I do this in a service and that method looks like this:
So my controller looks something like
In my client side code I do something like this (using the jQuery form plugin, but this would work with a generic $.ajax / $.post / $.get method as well…
And my showErrors function
Hope that helps.