#229 Polling for Changes
Aug 30, 2010 | 16 minutes | Ajax
If you have frequently changing data on the server side, it's helpful to automatically display this to the user as well. Here I show how to accomplish this with polling in jQuery.
- Download:
- source codeProject Files in Zip (107 KB)
- mp4Full Size H.264 Video (24.3 MB)
- m4vSmaller H.264 Video (16.5 MB)
- webmFull Size VP8 Video (41.4 MB)
- ogvFull Size Theora Video (34.3 MB)
Resources
bash
bundle install
rails g jquery:install
bundle install rails g jquery:install
Gemfile
gem 'jquery-rails'
gem 'jquery-rails'
comments_controller.rb
def index
@comments = Comment.where("article_id = ? and created_at > ?", params[:article_id], Time.at(params[:after].to_i + 1))
end
def index @comments = Comment.where("article_id = ? and created_at > ?", params[:article_id], Time.at(params[:after].to_i + 1)) end
layouts/application.html.erb
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
<%= javascript_include_tag :defaults %> <%= csrf_meta_tag %>
articles/show.html.erb
<div id="article" data-id="<%= @article.id %>">
...
<div class="comment" data-time="<%= comment.created_at.to_i %>">
<div id="article" data-id="<%= @article.id %>"> ... <div class="comment" data-time="<%= comment.created_at.to_i %>">
comments/index.js.erb
<% unless @comments.empty? %>
$("#comments").append("<%=raw escape_javascript(render(@comments)) %>");
$("#article h2").text($(".comment").length + " comments");
<% end %>
<% unless @comments.empty? %> $("#comments").append("<%=raw escape_javascript(render(@comments)) %>"); $("#article h2").text($(".comment").length + " comments"); <% end %>
javascript
$(function() {
if ($("#comments").length > 0) {
setTimeout(updateComments, 10000);
}
});
function updateComments () {
var article_id = $("#article").attr("data-id");
if ($(".comment").length > 0) {
var after = $(".comment:last-child").attr("data-time");
} else {
var after = "0";
}
$.getScript("/comments.js?article_id=" + article_id + "&after=" + after)
setTimeout(updateComments, 10000);
}
$(function() { if ($("#comments").length > 0) { setTimeout(updateComments, 10000); } }); function updateComments () { var article_id = $("#article").attr("data-id"); if ($(".comment").length > 0) { var after = $(".comment:last-child").attr("data-time"); } else { var after = "0"; } $.getScript("/comments.js?article_id=" + article_id + "&after=" + after) setTimeout(updateComments, 10000); }

