Many web applications use AJAX nowadays. In a typical scenario, one fills out a form, which is then submitted to the server. If you don't use AJAX or JavaScript is disabled, your form should still submit with no problems. And you receive a new page. If you use unobtrusive enhancement via JavaScript, the form is submitted to the server and the page is updated with the result without a full page reload.
While developing with Grails writing Java and Groovy code, I noticed that a typical pattern is to create two actions in a controller. One to handle normal HTTP POST (e.g. save action) and one to handle HTTP POST coming from an AJAX request (e.g. saveAjax action). The two actions are almost identical. They perform the same business logic. The only difference is what is returned from each action. A normal action renders a new page. An AJAX one returns whatever your flavor is: XML, JSON, HTML, plain text.
So is there a way to tell the requests (ordinary and AJAX) apart?
You guessed it, there is. AJAX request comes with a special header - X-Requested-With. I usually have my controllers to extend my BaseController, which has a couple of useful methods that I use. isAjax(request) is one of them. And this is what it looks like.
public static boolean isAjax(request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
I hope you'll find it useful. The all you need to do in your action is this:
def save = {
// business logic
// ...
if (isAjax(request)) {
render([ /* data */ ] as JSON)
}
else {
// render or redirect here
render(view: 'save', model: [ /* model data */ ])
}
}



