I have the following script in show.html.erb page, in order to update my progress bar. However it uses jQuery, and since jQuery is just loaded at the end of my application.html.erb layout, I cannot use it on my page. So I am requiring it also on my show.html.erb page before the script code.
It's clear that this is not the right way to do it. Where should I put my script code so as it's just loaded for this page? Another problem is that it uses information from the controller (@batch). If I move it to a js file in my assets folder, how can I access it?
The following code is placed at the end of show.html.erb
<%= javascript_include_tag "application" %>
<script type="text/javascript">
function progress(){
var progress = setInterval(function() {
var $bar = $('.bar');
var $pct = $('#pct');
$.get("<%= @batch.id %>/status.json", function(data){
if (data.status == "done") {
location.reload();
} else {
$bar.width(data.progress+"%");
$pct.text(data.progress+"%");
}
});
}, 800);
}
$(document).ready(function() {
$.get("<%= @batch.id %>/status.json", function(data) {
if (data.status == "processing") {
progress();
}
});
});
</script>
EDIT
Since now I'm getting batch_id, I can check if it exists to run the code:
$(document).ready(function() {
var batch_id = $("#batch").data("batch-id");
if (batch_id != null) {
$.get(batch_id + "/status.json", function(data) {
if (data.status == "processing") {
progress();
}
});
}
});