====== AJAX ======
Your have a form, and there is a '''' in it. You can add click callback to this button to submit the form by ajax. Here we only covered what I would like to talk about. For more details, go to [[http://api.jquery.com/jquery.ajax/]].
===== Client Code =====
$("#btn-save").click(function(){
var form = $(this).closest('form').get(0);
var jform = $(form);
$.ajax({
method:"post",
dataType: "json",
url: jform.attr('action'),
data: jform.serialize(),
success: function(data, textStatus, jqXHR) {
//DO YOU SUCCEE STUFF
},
error: function(jqXHR, textStatus, errorThrown){
//DO YOU FAIL STUFF
},
complete: function(jqXHR, textStatus){
//DO YOU FINAL STUFF NO MATTER SUCCESS OR ERROR
}
});
});
===== Server Code (in Grails) =====
Assume the client pass an 'id' field to the server. ''DomainObject'' can be any of your domain object that mapped to your data source, ''myService'' supposed to be any grails server that handle your business logic; MyException could be any of your own exception thrown by your business logic, and ''DateTimeTools'' is my own creation to handle date time related function call.
def myFunction(DomainObject domainObject) {
try {
myService.dosomething(domainObject)
response.status = 200
render([response: 'OK'] as JSON)
}catch (MyException e) {
response.status = 500
render([error: "Unable to XXXX XXXX XXXX. ${e.getMessage()}"] as JSON)
}catch (Exception e) {
log.error("Time: ${DateTimeTools.getSystemCurrentTime()} myFunction: ${e.getMessage()}", e)
response.status = 500
render([error: "Fail to XXXX XXXX XXXX. Please contact system admin for support."] as JSON)
}
}
===== jqXHR =====
A superset of XMLHTTPRequest. Here mainly, we talk about how to extract the response from the JSON server. In success, error, or complete callback function, you can extract the json response by ''jqXHR.responseJSON''.
Let says we want to extract the ''error'' message from the server for the above code, we can do the following in the error callback.
var responseJson = jqXHR.responseJSON;
alert(responseJson.error);