I saw this post about this issue: Auto Refresh a Html table every x seconds
Now, i am using rails, and i would like to do the same thing, but i want to tell rails that i want a remote page, i dont want it to load the full page. All i want is pretty much to simulate :remote => true action with ajax. I've tried it with regular ajax, and rails loads the whole page instead of just the relevant content that i want.
How can i do it ?
Your code should be something like this:
Your controller
def your_action
# your code goes here
end
(your_action.js.erb)
$("#div_id").html("<%= escape_javascript reder :partial => "your_partial_for_table" %>")
your_action.html.erb
<div id="div_id">
<%= render :partial => "your_partial_for_table" %>
</div>
_your_partial_for_table.html.erb
#your table goes here
<script>
$(function() {
$(document).ready(function() {
setInterval(function() {
jQuery.ajax({
url: "<path to your_action>",
type: "GET",
dataType: "script"
});
}, 30000); // In every 30 seconds
});
});
</script>
Server Sent Events
You may wish to use Server Sent Events (from HTML5):
Server-sent events (SSE) is a technology for where a browser gets automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML51 by the W3C.
This basically initiates something called ajax long-polling, which is where your JS will "ping" a particular URL every second, or number of seconds. The Ajax polling requests will then bring back particular response from the server, allowing you to use as you wish
--
Layout
I would do this:
#app/assets/javascripts/application.js
var source = new EventSource('path/to/your/endpoint');
source.addEventListener('message', function(e) {
//do something here
}, false);
#app/controllers/your_controller.rb
Class YourController < ApplicationController
include ActionController::Live
def your_action
response.headers['Content-Type'] = 'text/event-stream'
sse = Reloader::SSE.new(response.stream)
begin
sse.write(last_updated, event: 'results')
rescue IOError
# When the client disconnects, we'll get an IOError on write
ensure
sse.close
end
end
end
The trick here is that SSE's use their own content type - text/event-stream
to receive & parse the required data. This is compared with the standard mime
types which governs the typical HTTP protocol
I used this url for reference - you can then manipulate the text as it comes back from the server!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With