In the previous post we looked into creating AJAX-based progress indicator. But how do we supposed to tell the user if something goes wrong? Like a problem with backend connection, or database overload.
Here I will show you how to handle errors and display them easily in a fancy manner.
Simply put, you can’t use built-in Rails tools and redirect the user with flash message to some other page which would handle error messaging. We need to implement all this logic within a single page, without any redirects, because they spoil the AJAX fun.
So we would need:
divcontainer, hidden by default, which will be our placeholder for all error messages
JQuery to show/hide this container and to change its error message to an actual one
Some kind of timer which would help us to gracefully handle request timeouts
We take as an example the same Rails application, as in the previous post.
User clicks on a checkbox
Progress indicator is displayed
Some error raises
Progress indicator disappears
Modal window with error message and close button appears
User reads error message and closes the window
Step I - HTML & CSS
First, we add Twitter Bootstrap gem into our Gemfile:
And then install it:
$ bundle install
Now we need to install Modal Window Bootstrap plugin. So we download it and put into
Then we include it in our code, using
//= symbols here are not the comments:
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. ... //= require bootstrap-modal //= require_tree .
We can now move to our
app/views/layouts/application.html.erb file and add the appropriate
div placeholder there:
Now we have our
div placeholder in place together with the logic of showing, closing and making a window modal.
To do this we employ
app/views/shared/ajax-progress.js.erb file, which in the previous post was just a simple one-liner:
Good. The only case left to be taken care of is a request timeout. To handle it properly, we create a timer in
As you can see, we use 20-second timer and then display “Request Timeout.” error message.
Step III - Rails
The final piece that left is how to send the actual error message from Users Controller file
We’ve created a fancy AJAX-enabled error handling for our example application, using Rails, JQuery, and Twitter Bootstrap with a plugin.