AJAX post JSON data from Javascript to Grails
Solution 1
In your Ajax.Request options change
parameters:JSONstring,
to
postBody:JSONstring,
The problem with using parameters is that it URL encodes the data so that the request body ends up looking like this:
%7B%22id%22%3A%2223%22%2C%22name%22%3A%22Test%201%22%7D&_=
Instead of the desired (which is what you get with postBody):
{"id":"23","name":"Test 1"}
Solution 2
Good question mfloryan - I was doing the testing manually, i.e. not as part of a unit or integration test.
Thanks very much for the help hvgotcodes. I made the changes to my code as you have suggested, but unfortunately to no avail. Interestingly, if I print request.JSON I get {}
, whereas if I print request.json I get null
.
EDIT: By 'printing' I mean using: request.JSON.toString()
EDIT: Thank you all so much for the help. Once I'd made the final change John Wagenleitne suggested the code began working properly. I'm very grateful indeed for all your help.
Chris Claxton
Updated on August 31, 2022Comments
-
Chris Claxton over 1 year
I'm trying to POST JSON formatted data from Javascript (using Prototype) to Grails. My Javascript code is:
var JSONObject = new Object; JSONObject.id = "23"; JSONObject.name = "Test 1"; JSONstring = JSON.stringify(JSONObject); var url = "${createLink(controller:'testController', action:'receiveJson')}"; new Ajax.Request(url, { method:'post', contentType:'application/json', parameters:JSONstring, asynchronous:true, onSuccess: function (req) { sendInfoResponse(req.responseText); } });
and the code in my Grails controller is:
def receiveJson = { def json = request.JSON; }
However, the 'json' variable appears to be empty in my tests. I'd be so grateful if someone could explain what I'm doing wrong. Many thanks.
-
Katrine over 13 yearsDo you mean manual tests of the application or proper unit / integration tests?
-
-
clockworkgeek over 13 yearsOr you could do
parameters:JSONObject,
and leave outJSONstring
entirely, Prototype will encode it correctly for you. -
user2433701 over 13 years@clockworkgeek that will encode the object as key/value pairs: id=23&name=Test%201&_=. You could access this as params.id and params.name in the controller, but it wont be parsed as a JSON object via request.JSON which is what I think the original poster wanted.
-
JeffSea over 13 yearsIf the answer you referenced solved the problem, then you should mark the answer as accecpted.