[grails] setting cookies when render type is "contentType: text/json"
- by Robin Jamieson
Is it possible to set cookies on response when the return render type is set as json?
I can set cookies on the response object when returning with a standard render type and later on, I'm able to get it back on the subsequent request. However, if I were to set the cookies while rendering the return values as json, I can't seem to get back the cookie on the next request object. What's happening here?
These two actions work as expected with 'basicForm' performing a regular form post to the action, 'withRegularSubmit', when the user clicks submit.
// first action set the cookie and second action yields the originally set cookie
def regularAction = {
// using cookie plugin
response.setCookie("username-regular", "regularCookieUser123",604800);
return render(view: "basicForm");
}
// called by form post
def withRegularSubmit = {
def myCookie = request.getCookie("username-regular");
// returns the value 'regularCookieUser123'
return render(view: "resultView");
}
When I switch to setting the cookie just before returning from the response with json, I don't get the cookie back with the post.
The request starts by getting an html document that contains a form and when doc load event is fired, the following request is invoked via javascript with jQuery like this:
var someUrl = "http://localhost/jsonAction";
$.get(someUrl, function(jsonData) { // do some work with javascript}
The controller work:
// this action is called initially and returns an html doc with a form.
def loadJsonForm = {
return render(view: "jsonForm");
}
// called via javascript when the document load event is fired
def jsonAction = {
response.setCookie("username-json", "jsonCookieUser456",604800); // using cookie plugin
return render(contentType:'text/json') { 'pair'('myKey': "someValue") };
}
// called by form post
def withJsonSubmit = {
def myCookie = request.getCookie("username-json");
// got null value, expecting: jsonCookieUser456
return render(view: "resultView");
}
The data is returned to the server as a result of the user pressing the 'submit' button and not through a script. Prior to the submit of both 'withRegularSubmit' and 'withJsonSubmit', I see the cookies stored in the browser (Firefox) so I know they reached the client.