In background, I want it to reload and shows the number how many unread messages are there.
I want that without refreshing page. I mean using ajax.
If I had t
You will use setInterval to send the ajax request:
$(document).ready(function () {
// will call refreshPartial every 3 seconds
setInterval(refreshPartial, 3000)
});
// calls action refreshing the partial
function refreshPartial() {
$.ajax({
url: "whatever_controller/refresh_part"
})
}
Then you make an action in a controller like this:
def refresh_part
# get whatever data you need to a variable named @data
respond_to do |format|
format.js
end
end
then you will write a js file named refresh_part.js.haml
(you could erb instead of haml).
refresh_part.js.haml would look like this:
$('#part_you_want_to_refresh').html("#{escape_javascript(render 'name_of_partial', data: @data)}");
make sure you set the correct routes in routes.rb
.
FYI, refresh_part.js.erb would look like this:
$("#part").html("<%= escape_javascript(render 'partial', data: @data) %>");
instead of:
$('#part').html("#{escape_javascript(render 'partial', data: @data)}");
also, we can use the alias of "escape_javascript" to simplify this:
$("#part").html("<%= j(render 'partial', data: @data) %>");
Yes you can
<html>
<head>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(5000);">
<p>This page will refresh every 5 seconds. This is because we're using the 'onload' event to call our function. We are passing in the value '5000', which equals 5 seconds.</p>
<p>But hey, try not to annoy your users too much with unnecessary page refreshes every few seconds!</p>
</body>
</html>
Source: http://www.quackit.com/javascript/javascript_refresh_page.cfm