Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update progress bar in rails using jQuery

I'm a complete novice in JavaScript/jQuery and I believe it's a very simple question; however I'm not being able to accomplish it.

I have an asynchronous task being performed (by sidekiq) and it's progress is available by a method from the model (percentage_complete) that retrieves its progress from Redis.

I want to display a progress bar in model's show view, and I want it to update every x seconds using AJAX.

The progress bar is being displayed like this on the show.html.erb file:

<div class="progress">
  <div class="bar" style="width: <%= @model.percentage_complete %>%;"></div>
</div>

How can I set a jQuery script to update this attribute asynchronously?

EDIT

I also have a a :status attribute which is set do "done" when the task is complete. I would like to stop updating when that happens.

By reading my question it appears that I haven't tried nothing and just want someone to write the code for me. Let me add some comments:

  • I know I should use setInterval to update the attribute every "x" seconds
  • I know I should use $('.progress .bar').width(<%= @model.percentage_complete %>%) to set the new percentage

However, since I'm not familiar to jQuery and JavaScript, specially in Rails, I'm not sure if this script should be loaded in a view, or if it should be a view itself.

like image 269
João Daniel Avatar asked Jun 25 '26 04:06

João Daniel


1 Answers

I solved it by creating an action to retrieve the status

# GET /status/1.json
def status
  @batch = Batch.find(params[:id])

  respond_to do |format|
    format.json
  end
end

and using the following JavaScript:

<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>
like image 198
João Daniel Avatar answered Jun 27 '26 19:06

João Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!