0

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

imtiaz
  • 223
  • 1
  • 7

2 Answers2

0

Use :to_json method for Array

valRet1.to_json

or from controller:

respond_to do |format|
  format.json do
    render :json => valRet1
  end
end
Oleksandr Skrypnyk
  • 2,762
  • 1
  • 20
  • 25
0

Ok. I found that the following works:

valRet2 = [["'Sep 9, 1970'", 0],
  ["'Sep 14, 1970'", 0.94],
  ["'Sep 20, 1970'", 0.46]]

So the problem is partially solved. Still looking for a solution to return a json object that jQuery / javascript can understand by a call such as:

var returnedJson = <%= chart_data %>;
imtiaz
  • 223
  • 1
  • 7
  • Well, the correct answer to my query was in this post: http://stackoverflow.com/questions/3757457/handling-json-in-js-erb-template-in-rails-3. – imtiaz Oct 16 '11 at 16:08