title: How to assign and access a javascript variable in Rails using ajax
body: <p>I'm using the gon gem for rails, which allows you to save variables defined in a controller action and use them in your JavaScript. It works fine when I use it in non-Ajax settings, however, I'm having an issue with using it successfully when doing Ajax requests.</p>
  
  <p><strong>The problem</strong>: Ruby variables I assign to gon variables in the controller action when making Ajax requests come out as 'undefined' in the JavaScript.</p>
  
  <p><strong>The objective</strong>: I want to trigger an Ajax request on my page, which:
  1) hits an action in the controller, and assigns a Ruby variable to a gon variable.
  2) it then renders a js.erb file which executes JavaScript, part of which needs to take the Ruby variable defined in step 1, and treat it as a js variable.</p>
  
  <p><strong>here's the example action in step 1</strong>:</p>
  
  <pre><code>def some_action
   gon.my_ajax_var = {some: 'info'}
  end
  </code></pre>
  
  <p><strong>here's the example js.erb file it renders:</strong></p>
  
  <pre><code>/some_action.js.erb
  
  console.log('gon.my_ajax_var equals ' + gon.my_ajax_var)  //this doesn't work! comes out as 'undefined' when I expected {some: 'info'}
  </code></pre>
  
  <p>Any thoughts on how I fix this? I took a look at the gon.watch page, but I was confused as to whether that relates to this problem I'm having and how to implement the correct solution. Additionally, if there's a better way to do this without gon, I'm open to that as well.</p>
  
  <p>Thanks!</p>