Skip to content Skip to sidebar Skip to footer

Ajax Post Json Data From Javascript To Grails

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

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.

Solution 3:

I don't think you are invoking the Ajax.Request correctly. From the documentation, the parameters option:

"The parameters for the request, which will be encoded into the URL for a 'get' method, or into the request body for the other methods. This can be provided either as a URL-encoded string or as any Hash-compatible object (basically anything), with properties representing parameters."

I think you need to do something like

...
parameters: {json: JSONString}
...

and then in your controller

request.json

note the form of the parameters object literal - it tells the Prototype library to make the request key 'json' and the request value be the json string. You access the key off the request object in the controller.

EDIT -- I just realized you're javascript block is jacked up.

This:

varJSONObject = newObject;

should be something like

varJSONObject = newObject();
...

you might also be able to do just an object literal, so

var jsonObject = {};
....

Post a Comment for "Ajax Post Json Data From Javascript To Grails"