Note that there are some explanatory texts on larger screens.

plurals
  1. POreturning JSON from ruby helper function to javascript
    primarykey
    data
    text
    <p>I have a Ruby on Rails application. On click of a button I have some AJAX calls that should return with JSON.</p> <p>Here are the relevant lines of code:</p> <p>File "index.js.erb":</p> <pre><code>var myJson = &lt;%= chart_data %&gt;; </code></pre> <p>File "parameter_helper.rb":</p> <pre><code>module ParameterHelper def chart_data valRet1 = { :name =&gt; "Total Traffic", :data =&gt; [ ['Sep 9, 1970', 0], ['Sep 14, 1970', 0.94], ['Sep 20, 1970', 0.46] ] } valRet2 = [1, 2] return valRet1 end end </code></pre> <p>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.</p> <p>I played around with ActiveSupport::JSON.encode, jQuery.parseJSON, converting my JSON object to string and escaping quotes etc. Nothing seems to work.</p> <p>The following resulted in errors:</p> <pre><code>return '[["Sep 9, 1970", 0], ["Sep 14, 1970", 0.94], ["Sep 20, 1970", 0.46]]' </code></pre> <p>The following also resulted in errors:</p> <pre><code>result = [['Sep 9, 1970', 0], ['Sep 14, 1970', 0.94], ['Sep 20, 1970', 0.46]] return '"' + ActiveSupport::JSON.encode(result) + '"' </code></pre> <p>The following returned correctly:</p> <pre><code>return "[['Sep 9, 1970', 0], ['Sep 14, 1970', 0.94], ['Sep 20, 1970', 0.46]]" </code></pre> <p>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.</p> <p>Help will be appreciated.</p> <p>Environment:</p> <pre><code>OS: Windows 7 Rails: 3.1.0 Ruby: 1.9.2p290 (2011-07-09) [i386-mingw32] </code></pre> <p>Regards,</p> <p>Imtiaz</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload