Reputation: 539
I have a ruby on rails site and in that I have a variable called @number. The variable uses a api to grab a number and then displays it. The problem is that it only updates once every refresh. I need it to update every 10 seconds and I believe that it can be done in jquery/ajax. I have tried looking online but havent found anything similar or with rails. Thanks.
Upvotes: 1
Views: 1378
Reputation: 7333
If you have something like this in your template:
Hi you have <div id="my_number"><%= @number %></div> here?
one way to update that number would be to send an ajax request like this
var number = $("#my_number").value(); // get current number as displayed in template
// send the number to the server
$.ajax({
url: your_controller/check_number, // your controller
data: number, // data
success: success,
dataType: "script" // not 100% sure here might need to google
});
In your controller you could have a "check_number" action:
def check_number
@old_number = params[:number] // number from the template
@new_number = update_my_number // not sure what or how your number changes
respond_to do |format|
format.js // render your js.erb template
end
end
and finally in your js.erb template something like this:
<% if @old_number != @new_number %>
$("#my_number").value(<%= @new_number %>); // of course you can also do this in controller and just update everytime
<% end %>
and call for the x (5 seconds in this case) seconds per call just wrap it in:
window.setInterval(function(){
// call me here
}, 5000); // ms
EDIT: I assumed with api you meant something you have control over (your rails app), if that is not the case, you just need to hook into the success callback in the ajax method and update the variable with jquery.
Upvotes: 1