Okay, what i am looking for is a way to get an ajax script to run in the background of a page and look to see if there is a new record in the database and if there has grab that record and display that on my page.
i also do not want to use plugins i would rather do this myself as i prefer to learn how to do it and easier to make changes if i need it for something different in the future
im quite new to ajax and ruby on rails so a bit of explaining may be in order
This is my controller currently when i a user updates the content it changes without the page refreshing but what i want is it to also get new data
class NotificationsController < ApplicationController
# GET /notifications
# GET /notifications.json
def index
@notifications = Notification.all
end
def show
end
def update
@notification = Notification.find(params[:id])
@notification.update_attributes(:content => params[:content][:content])
respond_to do |format|
format.html { redirect_to notifications_path }
format.json { render json: @notification}
end
end
end
This is the js file
$(document).ready(function(){
$('input[type=submit]').on('click', function(event){
var form = $(this).parent('form');
event.preventDefault();
$.ajax({
type:"POST",
url: form.attr('action'),
data: form.serialize(),
success: function(data){
console.log('this worked')
$('#'+ data.id).html(data.content)
},
error: function(data){
console.log('failed')
},
dataType: 'JSON'
});
});
});
and this is my html file
<% content_for :titleheader do %>
NOTIFICATIONS
<% end %>
<h1>Listing Notifications</h1>
<% @notifications.each do |notification| %>
<%= form_for notification do |f| %>
<%= notification.id %>
<div id="<%= notification.id %>"><%=notification.content %></div>
<%= notification.read %>
<%= text_field "content", "content" %>
<%= f.submit "change status" %>
<% end %>
<% end %>
As you can tell i have not made a create action yet because im not sure if i am going to have to do this through ajax or something
help is very appreciated