Identifying ajax request or browser request in grails controller Identifying ajax request or browser request in grails controller ajax ajax

Identifying ajax request or browser request in grails controller


It's quite a common practice to add this dynamic method in your BootStrap.init closure:

    HttpServletRequest.metaClass.isXhr = {->         'XMLHttpRequest' == delegate.getHeader('X-Requested-With')    }

this allows you to test if the current request is an ajax call by doing:

if(request.xhr) { ... }

The simplest solution is to add something like this to your todo action:

if(!request.xhr) {     redirect(controller: 'auth', action: 'index')    return false}

You could also use filters/interceptors. I've built a solution where I annotated all actions that are ajax-only with a custom annotation, and then validated this in a filter.

Full example of grails-app/conf/BootStrap.groovy:

import javax.servlet.http.HttpServletRequestclass BootStrap {     def init = { servletContext ->        HttpServletRequest.metaClass.isXhr = {->            'XMLHttpRequest' == delegate.getHeader('X-Requested-With')        }     }     def destroy = {     }} 


Since Grails 1.1 an xhr property was added to the request object that allows you to detect AJAX requests. An example of it's usage is below:

def MyController {  def myAction() {    if (request.xhr) {      // send response to AJAX request      } else {      // send response to non-AJAX request    }  }}


The normal method is to have the ajax routine add a header or a query string to the request and detect that. If you're using a library for the ajax, it probably provides this already.

It looks like you're using prototype, which adds an X-Requested-With header set to 'XMLHttpRequest'; detecting that is probably your best bet.