views:

557

answers:

1

Hello, I'm trying to send the following data to the server but at the server side I don't see the json parameter that I'm sending. Can anyone tell me what I'm doing wrong?

Bellow you can see the code.

Prototype:

send_data_url = "change"

hash = $H({"blocks": [{"h": "2", "area": [{"width": "96%", "els": [{"title": "first", "mand": true}, {"title": "second", "mand": false}]}]}]});

var request_array_json = hash.toJSON();

new Ajax.Request(send_data_url, {
method: 'post',
parameters: request_array_json,
contentType: 'application/json;'
});

Rails:

def change()
debugger
my_json = ActiveSupport::JSON.decode(params["_json"])
end

In the controller I see that the params object does not have the json parameter.
It only shows the action and the controller:
{"action"=>"change", "id"=>nil, "controller"=>"default/test"}

Note: I'm using prototype 1.6 qnd rails 2.3.2.

Thanks in advance.
Best regards,
Hugo

A: 

I found a solution using a plugin called json_request.

To get this working nicely, I also wrapped Ajax.Request with a new class that can send complex JSON objects. Example code:

Ajax.JSON = Class.create(Ajax.Request, {
  initialize: function($super, url, options) {
    options = options || {};
    options.contentType = ‘application/x-www-form-urlencoded’;
    options.postBody = Object.toJSON(options.object);
    $super(url, options);
  }
});

new Ajax.JSON(url, { object: myObject });

Read more: http://labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/comment-page-1/#comment-143190#ixzz0n5iKnO60

Eric Nguyen