I need to seed a javascript variable to the controller. For example, if my code in the view is the following -
... <script type="text/javascript">
variable_test = 'hello'
</script>
...
I need the controller to get variable_test , like -
def hello
@variable_test = #Some code
# @variable_test => 'hello'
end
The view is hello of course, and 'Some code' is what I don't know how to do.
You can't send client side code to the controller unless you do a get, or post, of some sort. Try using jQuery's post or get methods. If you aren't using jQuery then you can do something like this:
var variable_test = 'hello';
var el = document.createElement('script');
el.setAttribute('src', 'path_to_controller' + '?variable_test=' + variable_test);
document.body.appendChild(el);
then in your controller you would do:
@varliable_test = params[:varliable_test]
The syntax may be a bit off, but you get the general idea.
First of all, you need to call the controller somehow. Either the data is in a form and you submit the form, or you make an AJAX call from javascript. In the first case, you'd want to use javascript to add a hidden input to the form with the name and value that you want. In the second case, the data you send with your AJAX request would need to include the name-value pair that you want. I can't get any more specific without knowing more about what you're doing; are you submitting a form or using AJAX, and if you're using AJAX are you using a javascript library, or using any of the built-in Rails helpers for ajax (e.g. remote_function).
Either way, though, you want to wind up with a request that includes the name-value pair "varliable_test=hello". Then you just do
@varliable_test = params[:varliable_test]
to access the value within your controller.
(I have to note, also, that presumably you mean "variable", not "varliable", but obviously that doesn't affect functionality so long as you're consistent.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With