If you ever wondered how this rotating thing works, you should definitely check this post. I will describe how to create AJAX-based progress indicator (or a progress bar) with Rails application.
No rocket science is involved here:
Indicator itself is an animated gif image
It is typically placed within hidden
divcontainer with position
fixedas a background
divat appropriate times
<form ... data-remote="true">)
Let’s assume that we have a simple Rails application where we want to manage users: list them, block them, and assign admin rights to them.
Here is the data model of
And here is how it looks:
What we want to do, though, is to update
is_admin fields using AJAX.
This is how we assume this would work:
User clicks on a checkbox
Progress indicator is displayed
After the field in the database has successfully updated, progress indicator disappears
Error message is shown in case of problems with the previous step (not covered in this chapter)
Step I - HTML & CSS
First of all, we add appropriate
Then we have to get gif image itself. I can recommend a very good site, where you can generate whatever progress indicator you want, with different shapes and colors.
The most difficult part here is to find the indicator to your heart’s consent. So when you finally choose it, put it in
In order to get our
div container working properly, we have to define its CSS. The Rails-way is to edit
So now we have our progress indicator image and container, which is hidden by default. Now we have to add some programming logic behind all this stuff.
First of all, we define AJAX-based form in our users view. I’m using
app/views/users/index.html.erb file with
<%= render @users %>, so we should change
app/views/users/_user.html.erb file, where all the logic is defined:
As I mentioned before, we want our indicator displayed after clicking on a checkbox. So we need to handle this event somehow. For this purpose we would use a file called
And, of course, we should include it in our
So now we have indicator displayed after clicking a checkbox. The next thing is to hide it after our action is completed.
We create AJAX response template
app/views/shared/ajax-progress.js.erb (I want to use it in several other places, such as collectors list, so I create it shared):
Step III - Rails
The final piece, that glues all the logic together, is an
update action in our
We created a basic progress bar functionality, using Rails, JQuery, and CSS. We haven’t touched error handling yet, which is very interesting and challenging itself in this AJAX-based environment.
Luckily, we have tools, such as Twitter Bootstrap components, which are going to help us a lot.