1

i'm using rails 4 and javascript and here's my question: i need to change the values of 3 divs using a button. The values of the divs are generated by a ruby function that came from the controller of that page. Code:

<% $number= randNumbers %>
<div id="1"><%= $number[0] %></div>
<div id="2"><%= $number[1] %></div>
<div id="3"><%= $number[2] %></div>
<button id="btn1" >Click me!</button>

Here's the ruby method

def randNumbers
n1=rand(1..10)
n2=rand(1..10)
n3=rand(1..10)
return array=[n1,n2,n3]
end

So i need to recall the ruby function to generate new random numbers everytime i click on the button "btn1" without reloading the page. I know that i have to use ajax or jquery, but i do not really know how to use it with ruby methods. Thanks for helping :D

Luke Smith
  • 83
  • 1
  • 1
  • 9
  • Please post your half-cooked code that you have for this purpose. – RAJ Jan 05 '16 at 12:05
  • Possible duplicate of [How to do an Ajax GET request to get data from rails and pass it to javascript(google maps)?](http://stackoverflow.com/questions/11589508/how-to-do-an-ajax-get-request-to-get-data-from-rails-and-pass-it-to-javascriptg) – Drenmi Jan 05 '16 at 12:43

1 Answers1

0

You can try the following:

HTML code in View:

Remove the code <% $number= randNumbers %>

Change the code to:

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<button id="btn1" >Click me!</button>

Javascript Code in View:

$( document ).ready(function() {
  call_ajax();
});

$("#btn1").click(function(){
  call_ajax();
});

function call_ajax(){
  $.ajax({ type:'POST', url:'/controller/get_random', data: {},
    success:function(data)
    {
      $("#1").text(data.arr[0])
      $("#2").text(data.arr[1])
      $("#3").text(data.arr[2])
    },
    error:function()
    {
      // Handle error if Ajax fails
    }
  });
}

Method in Controller:

def get_random
  n1=rand(1..10)
  n2=rand(1..10)
  n3=rand(1..10)
  array=[n1,n2,n3]
  render json: {arr: array}
end

Also add routes in routes.rb: post '/controller/get_random'

Radix
  • 2,527
  • 1
  • 19
  • 43
  • @LukeSmith Your always welcome. Although it would be helpful if you upvote and [accept](http://meta.stackexchange.com/q/5234) the answer. It's a SO way to say thanks. – Radix Jan 05 '16 at 17:19