Reputation: 470
I want to change the layout when there is an ajax request. So I setup an Filter for that:
class AjaxFilters {
def filters = {
ajaxify(controller: '*', action: '*') {
after = { Map model ->
if(model==null) {
model = new HashMap()
}
// only intercept AJAX requests
if (!request.xhr) {
model.put("layout", "mainUsers")
return true
}
// find our controller to see if the action is ajaxified
def artefact = grailsApplication
.getArtefactByLogicalPropertyName("Controller", controllerName)
if (!artefact) { return true }
// check if our action is ajaxified
def isAjaxified = artefact.clazz.declaredFields.find {
it.name == 'ajaxify'
} != null
def ajaxified = isAjaxified ? artefact.clazz?.ajaxify : []
if (actionName in ajaxified || '*' in ajaxified) {
model.put("layout", "ajax")
return false
}
return true
}
}
}
}
This creates a view model named "layout" which should define what layout to use.
Here is an example view which uses the layout model:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<meta name="layout" content="${layout}"/>
<title>Profile</title>
</head>
<body>
<h3>Edit Profile</h3>
</body>
</html>
This is the controller:
class SettingsController {
def springSecurityService
static ajaxify = ["profile", "account"]
def profile() {
User user = springSecurityService.currentUser
UserProfile profile = UserProfile.findByUser(user)
if(profile == null) {
flash.error="Profile not found."
return
}
[profile: profile, user: user]
}
}
A normal request works as expected, but when I try an ajax one the response is completly empty. Only headers are sent.
Upvotes: 0
Views: 765
Reputation: 3881
After your model.put("layout", "ajax")
you don't want to return false
but rather true
. Returning false
indicates the filter failed in some way and halts all further processing, which will result in an empty response being returned to the browser. If you return true
, the updated model will continue through the processing chain and be rendered in your gsp.
Upvotes: 1
Reputation: 7395
You are returning true or false for ajax requests which will return blank. You should convert the model object as JSON using render function or convert the model object to JSON and return it. You don't need to check if action is ajaxified; just return the JSON object.
Upvotes: 1