Search code examples
ruby-on-railsajaxruby-on-rails-5messageflash-message

How do I create a message that flashes after an AJAX form returns an error?


I'm using Rails 5. I want to create a message that flashes on my page after I submit an AJAX form and an error comes back. I'm not using twitter bootstrap and would only consider using that if it doesn't screw up any of the other styling I already have. Anyway, on my view I have this

<div id="error_explanation" class="alert alert-success"></div>

and in my controller I have this

displayError('#{error_msg}')

which invokes this coffee script ...

@displayError = (msg) ->
  ...

  $("#error_explanation").text(msg)

As you guess, right now, the message just displays in plain text . I would like it to flash and then disappear. How do I do that?


Solution

  • If you just need the message to fade out after a set amount of time, then change that last line of CoffeeScript to:

    $("#error_explanation").text(msg).delay(3000).fadeOut()
    

    If you need something a bit more complex (e.g. don't fade out if hovered, stacked notifications, dismiss button etc), or ready-styled - then you might want to investigate using a JS library such as toastr.