I have an app with a table at /index. This table is filled with records from the DB. There is another third party service that does a 'post' to this app and creates a new DB record. I want to display this record using AJAX on the /index page without the need to refresh the page.
The new records from the third party service come at a rate of 2 per minute. So I thought of implementing this using a timer loop (of 30 secs) in my javascript which will issue a get at /get_latest_leads and defined a controller action get_latest which gets the records entered/updated in the last 30 secs. Then using the ids (to check duplicate entries in case there are any). On the client side I will pre-pend these new records to the table using javascript.
controller
# GET /leads
# GET /leads.json
def index
@leads = Lead.find(:all, :conditions => {:is_valid => true}, :order => "id DESC").paginate(:per_page => 30, :page => params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render json: @leads }
format.js
end
end
def get_latest
logger.info "in get_latest"
@leads = Lead.where('updated_at > ?', Time.now - 30.seconds)
@leads.each { |lead|
logger.info "#{lead.name}"
}
respond_to do |format|
format.json { render json: @leads }
end
end
routes.rb
get 'get_latest_leads', :to => 'leads#get_latest', as: :get_latest_leads
index.js.erb
alert("here1");
setInterval(
function(){
new Ajax.Request('get_latest_leads' + '.json', {
alert("here2");
method: 'get',
onSuccess: function(transport){
var leads = transport.response.responseJSON;
// insert the last checked time into <div id='time'></div>
// $('time').innerHTML = records.time;
// loop over response JSON and do what you want with the data
leads.each(function(lead){
$$('table#leads').insert({
top: '<tr><td>'+lead.attribute+'</td></tr>';
});
});
}
});
},
30000
);
The problem is that my js is not being called at all and there is no error on browser/server side. When I do a manual request from my browser at /get_latest_leads.json, it gets me the latest leads as a JSON. But my js is not calling it. Can you please tell me what is going wrong?
UPDATE:
I followed instructions from here and moved my js in the app tree accordingly to assets/javascripts/leads/index.js
This made the call successful and now I do get the alerts at every 30 seconds, meaning the function is working. However, now I am getting an "uncaught reference error ajax is not defined".