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 */ ])
}
}
6 comments:
Ajax has provided the java developers with a runtime functionality which seems better and feels better to the user. This post helps in real sense to get to know about detecting ajax request.
Great post - found your code after trawling through the Grails docs without a mention on unobtrusive javascript code. Thanks.
Thanks! I've tested this using IE6/7/8 and current versions of FF,Safari,Chrome and Opera
Thanks, just what I was looking for.
but we can't use this for critical solution because anyone can easily set a header while requesting from browser.
With AJAX, it is possible to update parts of a web page, without reloading the whole page.Definitely I will be come back on this blog to know more about programming language.
Thanks for this.
Post a Comment