1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.