Send javascript variable to rails helper method

1k views Asked by At

I have an array of video names, I want to grab a random video name from this array. But when I call a helper method to do all this, I get the same random number, and random video each time.

I believe this is because the helper method is only called once even though I'm trying to "call it" multiple times, it's just the results of that method that are "called" multiple times.

So what I'm thinking is to find a way to send a JavaScript variable to the helper method, but I have no idea (nor does Google) of how best to do this.

To keep it simple, with just trying to obtain a new random number each time:

JS:

function randomNumber() {
    alert("<%= random_number %>");
}

setTimeout(function(){
    randomNumber();
}, 2000);

html.erb:

helper_method :random_number
def random_number
  rand(0..10)
end

The same random number is shown each time.

1

There are 1 answers

0
Richard Peck On

Requests

Rails works on "requests"

Because Rails is server-side, it works with these requests to "render" the pages / views you see on your screen. Each request is treated individually, meaning that you have to pass it everything the server will need to render the correct view for you

The problem you're alluding to is you're trying to use data which has already been rendered. The "helper" view was rendered when you sent the HTTP request to Rails, and consequently is going to use the same data over and over


Client-Side Vs Server-Side

The problems you're seeing come from the difference between client-side (JS) and server-side (Rails). The difference is that you can't access Rails from JS, unless you send a "request" (probably via ajax)

In order to trigger Rails from the client-side, you have to send a request. That's either done with a browser click, or Ajax


Your Question

You're trying to load a random number between 1 & 10 from Rails

This can be handled entirely by JS if you use the right functions / code

Alternatively, you can use Ajax to request the helper from Rails, but this is highly inefficient, as it will send an unnecessary request to the server