Home > Software engineering >  Rails show flash message before controller action / loading info
Rails show flash message before controller action / loading info

Time:12-02

What I want to do is actually very simple but i don't know how to achieve it.

The user can enter information and click on "bulk create" and create multiple objects. when finished, the user sees a flash message saying "Saved successfully". But the saving can sometimes take a bit longer, so I also want to show a message saying "Saving..." so the user knows something happens.

It should go like this:

  1. user enters information
  2. user clicks on create button
  3. flash saying "Saving data..." appears
  4. Controller finished and new flash appears that says "Saved successfully" (or "couldn't save etc." when it failed)

I have 1, 2, and 4, but I don't know how to achieve 3 since there is no redirect or something like that... Can I trigger a flash via javascript maybe? Or do I have to do something completely different?

CodePudding user response:

What i propose is creating a div element in your view and placing it where your want your alert to appear. When button is clicked make AJAX post request:

$(".button").click(function () {
      $("#alert_div").innerHTML = "Saving";
      $.ajax({
        url: '/form_submit',
        type: 'POST',
        data: formData,
        success: function(){ 
           $("#alert_div").innerHTML = "Saved successfully";
        },
        error: function(){
           $("#alert_div").innerHTML = "Something went wrong!";
        }
      });       
});
  • Related