Skip to content

Instantly share code, notes, and snippets.

@athap
Created September 1, 2012 17:43
Show Gist options
  • Save athap/3581369 to your computer and use it in GitHub Desktop.
Save athap/3581369 to your computer and use it in GitHub Desktop.
Rails like flash messages using JQuery for JS or AJAX calls
# This gist shows how to display Rails like flash messages while handling AJAX or JS requests
# Note - This might not be the best way to do this but it works for me
Step 1. Create a partial which will contain the message to be displayed
Example - _success.html.erb
<div id="flash_message">
<p>Success</p>
</div>
Step 2. In the Controller, add code to call this partial on a JS request
Example - ExampleController.rb
class ExampleController < ApplicationController
.
.
.
def example_action
.
.
respond_to |format|
# This call will search for action success, if not present, it will call the template named success.js
# Note - success.js is created in step 3
format.js { render :action => 'success' if some_condition }
end
end
end
Step 3. Create a file called success.js which will render the flash message
Example - success.js.erb
$("#element_where_flash_to_appear").prepend(
$("<%= escape_javascript(render :partial => 'success') %>").
hide().fadeIn(1000, function(){
$(this).remove();
})
);
Step 4. CSS for flash message
#flash_message {
text-align: center;
background: #ffe;
width:100%;
margin-left:auto;
margin-right:auto;
border:1px solid gray;
margin:0px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment