I am using Ruby on Rails 3.0.10 and jQuery 1.6. I am trying to implement an AJAX HTTP request and I have a doubt on stating the data parameter of that request.
Let say that I have JavaScript code like the following:
$jQ.ajax({
type: '...',
url: '...',
data: '...', // Here I would like to state the
error: function(jqXHR, textStatus, errorThrown) {
...
},
success: function(data, textStatus, jqXHR) {
...
}
});
So, I may populate the data parameter like this:
data: 'a=1&b=2&c=3'
data: '<%= data_value %>' # Example 'data_values' value: a=1&b=2&c=3
I read both the Ruby (on Rails) and jQuery documentation and those frameworks seem to deal with data differently: the first “tends to use” hashes, the second an “as-like Json” data or directly a URL query string (as in the above example).
But, how I should state\handle data parameter values for a jQuery.ajax request so to pass to it a “converted” Ruby hash? That is, what is the common pratique adopted in order to populate the data parameter so to take advantage of both jQuery AJAX and Ruby hashes (or some other data structure)?
In few words, what I would like to make is to pass a variable (maybe a Ruby hash) to the jQuery data parameter and convert it so to be “compatible” with the jQuery system related to that data. Maybe I should use something like the following:
# data_value = {:a => 1, :b => 2, :c => 3}
data: '<%= convert_to_ajax_data(data_value) %>'
If I use some code like the following
data_value.as_json {"layout"=>"false"}
data_value.to_json {"layout":false}
it doesn’t work as expected.
By using the to_json method the problem is that the outputted code is something like the following:
data: {"a":1, "b":2, "c":3} # '"' chars are replaced with "
How can I avoid the replacement?
You can convert hashes in Rails to JSON format like this
data.to_jsonAll params submitted via JavaScript are just regular
paramshash in Rails.If you need serialized data in JavaScript just format your hash to a string with something like: