Is it possible to refresh partial frequently using Ajax?

You will use setInterval to send the ajax request:

$(document).ready(function () {
    // will call refreshPartial every 3 seconds
    setInterval(refreshPartial, 3000)

});

// calls action refreshing the partial
function refreshPartial() {
  $.ajax({
    url: "whatever_controller/refresh_part"
 })
}

Then you make an action in a controller like this:

def refresh_part
  # get whatever data you need to a variable named @data
  respond_to do |format|
    format.js
  end
end

then you will write a js file named refresh_part.js.haml (you could erb instead of haml).

refresh_part.js.haml would look like this:

$('#part_you_want_to_refresh').html("#{escape_javascript(render 'name_of_partial', data: @data)}");

make sure you set the correct routes in routes.rb.

Leave a Comment