Rails 2.1 JSON and mootools 1.2 Request.JSON

The short answer is no. Fortunately, the lengthy answer involves a compatibility library for mootools and a few additional options to legacy Json.Remote from mootools 1.11.

First, you’ll need to obtain the mootools 1.2 compatibility library, which includes an implementation of Json.Request that behaves in a manner conducive for sending JSON to an application server.

Next, make a one line change to mootools-compat-core.js:

--- a/public/javascripts/mootools-compat-core.js
+++ b/public/javascripts/mootools-compat-core.js
@@ -171,7 +171,7 @@ JSON.Remote = new Class({
 
        send: function(data){
                if (!this.check(arguments.callee, data)) return this;
-               return this.parent({url: this.url, data: {json: Json.encode(data)
+               return this.parent({url: this.url, data: Json.encode(data)});
        },
 
        failure: function(){

The above change saves you from Request class.

switch ($type(data)){
	case 'element': data = $(data).toQueryString(); break;
	case 'object': case 'hash': data = Hash.toQueryString(data);
}

Otherwise, the data is x-www-form-urlencoded, preventing you from using an application/json Content-type header.

Finally, we can use Json.Remote.

new Json.Remote('/app/server/path', {
	urlEncoded:false, // can't set Content-type otherwise
	headers:{
		'Content-type':'application/json'
	}
}).send({'wrapper':['data', 'stuff']});

Notice the wrapper hash key wraps otherwise naked JSON, so it is available in Rails by that key. Now Rails will automatically parse the application/json payload of the request and provide you with:

>> ActiveSupport::JSON.decode("{\"wrapper\":[\"data\",\"stuff\"]}")
=> {"wrapper"=>["data", "stuff"]}

Lovely!

Post a Comment

Your email is never shared. Required fields are marked *

*
*