Kohl
Kohl

Reputation: 87

Unobtrusive Flash Messages with Ajax

I am using leonid shevtsov's unobtrusive_flash gem in my app and everything works except for when their is an error. In my create.js.erb file for the post I am trying to,well,'post', the code is :

$('#post-it-note').prepend("<%= j (render partial: 'static/post_template',locals: {:post => @post}) %>");

UnobtrusiveFlash.showFlashMessage('Thanks for sharing!', {type: 'success'})

I have tried adding another line of code for errors, but haven't succeeded. The code for errors in my html partial view that has the form is:

<% if @post.errors.any? %>
  <div id="error_explanation">
    <ul>
        <%= @post.errors.full_messages.each do |msg| %>
           <li> <%= msg %></li>
        <% end %>
    </ul>
  </div>
<% end %>

FYI: I am getting ActionView Template Errors because of the validations I have set up.

I even tried adding flash.now messages but I still cannot figure out the right way. If someone has experience with this gem and showing flash messages for errors, please share. I know regular flash messages are visible only on page redirects/reloads. Thanks!

Upvotes: 2

Views: 423

Answers (1)

Stephen Horvath
Stephen Horvath

Reputation: 5588

It's because unobtrusive_flash doesn't handle ajax errors on the javascript side. If you want to handle ajax errors you need to add a callback in your javascript.

$(document).ajaxError(function(event,request,options) {
    UnobtrusiveFlash.showFlashFromCookies();
});

Upvotes: 2

Related Questions