I have a Ruby on Rails application. On click of a button I have some AJAX calls that should return with JSON.
Here are the relevant lines of code:
File "index.js.erb":
var myJson = <%= chart_data %>;
File "parameter_helper.rb":
module ParameterHelper
def chart_data
valRet1 = {
:name => "Total Traffic",
:data => [
['Sep 9, 1970', 0],
['Sep 14, 1970', 0.94],
['Sep 20, 1970', 0.46]
]
}
valRet2 = [1, 2]
return valRet1
end
end
The problem is that when I return valRet2 from chart_data, I get the required array in the index.js.erb file. But if I try returning valRet1, I get errors.
I played around with ActiveSupport::JSON.encode, jQuery.parseJSON, converting my JSON object to string and escaping quotes etc. Nothing seems to work.
The following resulted in errors:
return '[["Sep 9, 1970", 0],
["Sep 14, 1970", 0.94],
["Sep 20, 1970", 0.46]]'
The following also resulted in errors:
result = [['Sep 9, 1970', 0],
['Sep 14, 1970', 0.94],
['Sep 20, 1970', 0.46]]
return '"' + ActiveSupport::JSON.encode(result) + '"'
The following returned correctly:
return "[['Sep 9, 1970', 0],
['Sep 14, 1970', 0.94],
['Sep 20, 1970', 0.46]]"
The array (preferably hash) needs to be made on the fly (taking values from database) and hence cannot be a literal as in the case of correctly returned data above.
Help will be appreciated.
Environment:
OS: Windows 7
Rails: 3.1.0
Ruby: 1.9.2p290 (2011-07-09) [i386-mingw32]
Regards,
Imtiaz