Skip to content

Instantly share code, notes, and snippets.

@miguelperez
Created April 14, 2012 16:19
Show Gist options
  • Select an option

  • Save miguelperez/2385542 to your computer and use it in GitHub Desktop.

Select an option

Save miguelperez/2385542 to your computer and use it in GitHub Desktop.
Adding flash messages to headers upon xhr requests with ICanHaz and Jquery
//this is for the preloader gif
.loading{
position: fixed;
right: 5px;
bottom: 5px;
display:none;
}
<div class='loading'><%= image_tag('site/ajax-loader.gif') %></div>
<% content_for :templates do %>
<script type="text/html" charset="utf-8" id='flash_message'>
{{#notifications}}
<div class="alert alert-{{flash_type}}">
<a class="close" data-dismiss="alert">×</a>
<h4 class="alert-heading">{{title}}</h4>
{{message}}
</div>
{{/notifications}}
</script>
<% end %>
<%= yield :templates %>
$(document).ready(function(){
window.setAjaxHandlers = function(){
// whenever an AJAX request starts this will be called
$('.loading').ajaxStart(function() {
$(this).show();
});
// whenever an AJAX request stops this will be called
$('.loading').ajaxStop(function() {
$(this).hide();
});
// whenever an AJAX request completes this will be called
$(".loading").ajaxComplete(function(e, xhr, settings) {
var messages;
if(messages = $.parseJSON(xhr.getResponseHeader('X-Flash-Messages'))){
$('#flash-messages').append(ich.flash_message({notifications: messages}));
}
});
}
window.setAjaxHandlers();
});
after_filter :flash_to_headers
protected
#If the request is an XHR we will store the flash messages in the response headers
def flash_to_headers
return true unless request.xhr?
#avoiding XSS injections via flash
flash_json = flash.inject([]) do |acc, (k, v)|
flash_type = k.eql?(:alert) ? 'error' : 'notice';
title = k.eql?(:alert) ? 'Oops' : 'Success'
acc.push({:flash_type => flash_type, :title => title, :message => ERB::Util.h(v)})
acc
end.to_json
response.headers['X-Flash-Messages'] = flash_json
flash.discard # don't want the flash to appear when you reload page
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment