Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying ajax request or browser request in grails controller

I am developing a grails application which uses lot of ajax.If the request is ajax call then it should give response(this part is working), however if I type in the URL in the browser it should take me to the home/index page instead of the requested page.Below is the sample gsp code for ajax call.

<g:remoteFunction action="list" controller="todo" update="todo-ajax">

<div id ="todo-ajax">
//ajax call rendered in this area
</div>

if we type http://localhost:8080/Dash/todo/list in the browser URL bar, the controller should redirect to http://localhost:8080/Dash/auth/index

How to validate this in controller.

like image 287
DonX Avatar asked Mar 20 '09 05:03

DonX


People also ask

What is the difference between Web browser request and AJAX call request?

AJAX stands for asynchronous javascript and XML so if you are using javascript to load data after the browser request has finished you are doing AJAX. REST on the other hand stands for Representational State Transfer which as Stefan Billet pointed out uses HTTP requests to transfer data.

What type of requests does AJAX use between the server and the browser?

AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)


1 Answers

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.HttpServletRequest

class BootStrap {

     def init = { servletContext ->

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

     }
     def destroy = {
     }
} 
like image 185
Siegfried Puchbauer Avatar answered Nov 02 '22 19:11

Siegfried Puchbauer