1

I have the following variable defined in my Rails controller:

$PATH

In JavaScript I would like to change the value of this variable:

<script>
   $("#resetDefaults").click(function(){
       $PATH = '3'; //try 1
       <%= $PATH %> = '3'; // try 2
   });
</script>

I have tried both of the above statements and can't figure out how to do it.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • 3
    I think you may be confused by the 'global' term -- here, it refers to a variable available in all contexts of the Ruby process running your rails app. As JavaScript runs on a client browser, it is removed several levels from that process, so if you want to do this, you will need to set up specific routes and methods to change this variable. HOWEVER - I can't think of any circumstances where this would be a good idea. Could you describe the problem you are trying to solve? – Zach Kemp Jun 19 '13 at 16:22
  • +1 @ZachKemp for "HOWEVER - I can't think of any circumstances where this would be a good idea." – the Tin Man Jun 19 '13 at 17:35

2 Answers2

3

A global variable is only global in the Ruby code that is executed on the server.

You're running JavaScript code in the browser. That code has no direct access to variables on the server.

If you wish to change some state (variable) on the server, you need to call a Rails controller method from your JavaScript code. I.e., you need to do an AJAX call to the server from the browser. Something like this:

$("#resetDefaults").click(function() {
   $.ajax({ url: "<%= url_for(:action => 'update_path_var') %>" });
   return false;
});

Then in the controller you have something like:

def update_path_var
  $PATH = 1234
  render :nothing => true
end

http://api.jquery.com/jQuery.ajax/
http://apidock.com/rails/ActionController/Base/url_for

BTW, in general using global variables in Ruby is not considered good coding practice, unless there is some very specific reason for it.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Casper
  • 33,403
  • 4
  • 84
  • 79
  • can i do this without changing the view? –  Jun 19 '13 at 16:49
  • @SamanthaKlonaris Hm..what do you mean without changing the view? You have to change the code in the view. The click method needs to call the controller. – Casper Jun 19 '13 at 16:53
  • i mean rendering a new view –  Jun 19 '13 at 16:56
  • Yes. That's the idea with an AJAX call. It doesn't require the browser to go to a new URL (view). I think what you want is `return false` on the `click` event. If what you did was attach the click to a link element it will prevent the link from being followed. So the browser won't go to a new page. I updated the answer. – Casper Jun 19 '13 at 17:00
0

There is no way to achieve that. I think you should do some introduction to web programming course.

Mike Szyndel
  • 10,461
  • 10
  • 47
  • 63