4

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.

The problem: Ruby variables I assign to gon variables in the controller action when making Ajax requests come out as 'undefined' in the JavaScript.

The objective: 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.

here's the example action in step 1:

def some_action
 gon.my_ajax_var = {some: 'info'}
end

here's the example js.erb file it renders:

/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'}

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.

Thanks!

2 Answers 2

2

I ended up solving this by doing the following:

In my controller:

def some_action
  @my_ajax_var = {some: 'info'}.to_json
end

In my corresponding view: /some_action.js.erb

var my_ajax_var = <%= @my_ajax_var.html_safe %>

Would've been nice to have piggybacked off the gon gem, but this got the job done.

Sign up to request clarification or add additional context in comments.

Comments

-1

It's some time ago that I used erb templates, but I think you need to add tags in your erb-file.

/some_action.js.erb

console.log('gon.my_ajax_var equals ' + <%= gon.my_ajax_var %>)

1 Comment

friedi, just tried that, but this error was thrown: "undefined local variable or method `gon' for #<<Class:0x007fbfea377240>:0x007fbfe91c9958>". That error makes sense to me, as gon is supposed to only be defined as a js variable and not a ruby variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.