I've been working with Rails for a couple of years, but this is my first attempt at AJAX and Javascript. I spent a huge amount of time reading various web sites, trying to figuring out what goes where & what it's supposed to do.
I'm trying to make the 'refreshme' div in edit.html.erb in a Rails 4 app refresh every time the 'turn' field in the 'stories' table changes. So I wrote a setInterval() function in story.js to check @story.turn & refresh. I can get it to refresh every 10s, but I only want the code to check the value of story.turn every 10s, & refresh only if the value has changed.
routes.rb (Is this right?)
match '/stories/:id/refresh' => "stories#refresh", :as => :story_refresh, via: 'post'
refresh.html.erb (in views/stories - I have no clue what belongs here)
<div class="pollme" data-story-id="<%[email protected] %>" data-story-turn="<%[email protected] %>" >
<%[email protected] %> // This gets changed based on what other users are editing
</div>
edit.html.erb (views/stories) - show.html.erb refreshes nicely into this div
<div class="refreshme" data-story-id="<%[email protected] %>" data-story-turn="<%[email protected] %>" >
<%= render 'shared/micropost_form' %>
</div>
story.js
$(document).on("page:change", function() {
var $turn;
$turn = $('.refreshme').data('story-turn');
refreshStories = function(){
$.ajax({
type: "POST",
data: { }, // I'm sure something important goes here to get @story.turn out of the stories table
url: "/stories/"+$('.refreshme').data('story-id')+"/refresh"
}).done(function(result) {
alert('done' );
$turn = ; // Not sure what data{} can return
})
if ($('.refreshme').data('story-turn') != $turn) {
$.ajax({
type: "GET", // helps show.html.erb get refreshed into refreshme div in edit.html.erb
url: "/stories/"+$('.refreshme').data('story-id')
}).done(function(result) {
var $sentence_requests = $('.refreshme');
if ($sentence_requests.length > 0) {
$sentence_requests.html(result);
alert('UPDATED micropost requests ') ;
} else {
}
})
}
};
setInterval(refreshStories, 10000);
});
stories_controller.rb
def refresh
@story = Story.find(params[:id])
respond_to do |format|
format.json { }
format.html { }
end
end
def edit
@story = Story.find(params[:id])
@micropost = @story.microposts.build
respond_to do |format|
format.json { }
format.html { }
end
end
In story.js, the GET function executes, however the POST function does not. I'm not sure what I'm supposed to 'POST' (I thought I was 'GETting' a value from the database, but I guess not).
I think POST is the AJAX function I need to obtain @story.turn from the stories table, but don't know how to make it do anything. Do I also need GET to refresh? I've been kludging this code for weeks now, this seems like something I should've figured out by now. Any help would be greatly appreciated.
If you put this on a public github repo, people could see your code in-context, and also send a pull request demonstrating how they'd do it.