Rails doesn't display flash messages after ajax call

Donovan

I'm writing a rails 4.0.2 app, and am trying to get a Flash notice to display in my view after an AJAX event.

In my view I display a calendar with days a user can click on. When they do so, I fire an AJAX event via an onclick event handler which updates my model, either adding or removing a record. After firing the event, I complete a page refresh in order to display the updated results.

I found I had to do a page refresh during the JS click event in order to get the view to update properly. A redirect or render in the controller alone wasn't enough.

So, to that effect, I have set a Flash notice in my controller...

def set_conflicts
  @conflict = @member.conflicts.for_date(params[:date]).first

  if @conflict
    @conflict.destroy
  else
    conflict_date = Date.parse(params[:date])
    unless Conflict.create(
        month: conflict_date.month,
        day:   conflict_date.day,
        year:  conflict_date.year,
        member: @member
    )
      flash[:alert] = 'Oops, there was a problem updating conflicts'
    end
  end
  flash[:notice] = 'This is a test!'
  redirect_to manage_member_conflicts_path(@member)
end

... and have included the following flash display logic in my application.haml...

...
%body
  = p flash.inspect
  - flash.each do |type, message|
    = content_tag(:div, message, :class => "flash-#{type}")

  = render 'devise/menu/login_items'
  = yield

Note: I use HAML instead of ERB in my views

Yet, no matter what I try, the Flash message does not display. Everything else works as expected except the flash message, and I haven't been able to figure out why.

I suspect it's got something to do with the AJAX refresh I'm doing combined with the redirect (and maybe even turbolinks) but I've looked through other answers here on SO and simply can't get it to work. Clearly, I'm missing something.

Here's the JS click handler (it's pretty simple):

window.calendarClick = (eventDate, linkURL) ->
  event = $(document.getElementById(eventDate))
  event.toggleClass('selected')

  # Set or Remove conflicts
  $.ajax
    url: linkURL
    data:
      date: eventDate

  # Refresh the page
  $.ajax
    url: '',
    context: document.body,
    success: (s,x) ->
      $(this).html(s)
Richard Peck

Firstly, thanks for comprehensive question

Here is an equally comprehensive answer: How do you handle Rail's flash with Ajax requests?


Ajax

I'd seriously look at your Ajax refresh process. Refreshing the whole page is super inefficient, and I think covering a deeper issue

Why don't you try using a .js.erb file in the views folder, to handle JS directly by the method:

def set_conflicts
  @conflict = @member.conflicts.for_date(params[:date]).first

  if @conflict
    @conflict.destroy
  else
    conflict_date = Date.parse(params[:date])
    unless Conflict.create(
        month: conflict_date.month,
        day:   conflict_date.day,
        year:  conflict_date.year,
        member: @member
    )
      flash[:alert] = 'Oops, there was a problem updating conflicts'
    end
  end
  flash[:notice] = 'This is a test!'

  respond_to do |format|
      format.html { redirect_to manage_member_conflicts_path(@member) }
      format.js 
  end
end

#app/views/controller/set_conflicts.js.erb
$("#your_element").html(<%=j render manage_member_conflicts_path(@member) ) %>);

Response

Although I don't know this for sure, I know the Flash objects are handled by ActionDispatch::Flash middleware. I believe this is not handled for XHR in the same way as standard HTTP requests, consequently preventing Flash from being shown in your response

This means you'll have to do something to pass the Flash object through your Ajax request. And according to the question I posted at the top of this answer, you can use the response headers to do it:

class ApplicationController < ActionController::Base
after_filter :flash_to_headers

def flash_to_headers
  return unless request.xhr?
  response.headers['X-Message'] = flash[:error]  unless flash[:error].blank?
  # repeat for other flash types...

  flash.discard  # don't want the flash to appear when you reload page
end

$(document).ajaxError(function(event, request) {
  var msg = request.getResponseHeader('X-Message');
  if (msg) alert(msg);
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Handle Rails flash messages after AJAX calls using ReactJS

From Dev

Rails ajax forms + flash messages

From Dev

After an AJAX call, the next AJAX call doesn't work

From Dev

Display flash messages after login/logout

From Dev

Display flash messages after submiting a php form

From Dev

Yii flash messages doesn't work after redirect if set custom sessions path

From Dev

Ajax polling: Doesn't display alert box [rails]

From Dev

Rails / Bootstrap / HAML - How to convert this code to display flash messages to HAML?

From Dev

Change inner text after ajax call back doesn't work?

From Dev

Jquery function doesn't work after Ajax call

From Dev

addClass() function doesn't work after ajax call

From Dev

AJAX call doesn't work after submitting a form

From Dev

Chromium doesn't display Flash in Debian Wheezy

From Dev

Rails how to show flash messages after respond_with

From Dev

display flash and error message after ajax request Laravel

From Dev

Rails Flash doesn't behave as what the Rails Guide says

From Dev

AJAX call doesn't call alerts

From Dev

auto hide the flash messages in rails

From Dev

Rails Wicked Gem - Flash Messages

From Dev

Rails: Flash Messages not appearing anywhere

From Dev

Rails 4 page reload after ajax call

From Dev

Rails - form doesn't submit any data during AJAX call - file upload - 422 status code

From Dev

jquery datepicker doesn't work after ajax call if its already on page

From Dev

Click function doesn't work after ajax call in dynamic element (Backbone)

From Dev

Click function doesn't work after ajax call in dynamic element (Backbone)

From Dev

Function call doesn't display cout

From Dev

Rails 4 ajax flash messages cause strange behaviour for non xhr requests

From Dev

Rails 4 ajax flash messages cause strange behaviour for non xhr requests

From Dev

Ajax Call Worked; Doesn't Work Anymore

Related Related

  1. 1

    Handle Rails flash messages after AJAX calls using ReactJS

  2. 2

    Rails ajax forms + flash messages

  3. 3

    After an AJAX call, the next AJAX call doesn't work

  4. 4

    Display flash messages after login/logout

  5. 5

    Display flash messages after submiting a php form

  6. 6

    Yii flash messages doesn't work after redirect if set custom sessions path

  7. 7

    Ajax polling: Doesn't display alert box [rails]

  8. 8

    Rails / Bootstrap / HAML - How to convert this code to display flash messages to HAML?

  9. 9

    Change inner text after ajax call back doesn't work?

  10. 10

    Jquery function doesn't work after Ajax call

  11. 11

    addClass() function doesn't work after ajax call

  12. 12

    AJAX call doesn't work after submitting a form

  13. 13

    Chromium doesn't display Flash in Debian Wheezy

  14. 14

    Rails how to show flash messages after respond_with

  15. 15

    display flash and error message after ajax request Laravel

  16. 16

    Rails Flash doesn't behave as what the Rails Guide says

  17. 17

    AJAX call doesn't call alerts

  18. 18

    auto hide the flash messages in rails

  19. 19

    Rails Wicked Gem - Flash Messages

  20. 20

    Rails: Flash Messages not appearing anywhere

  21. 21

    Rails 4 page reload after ajax call

  22. 22

    Rails - form doesn't submit any data during AJAX call - file upload - 422 status code

  23. 23

    jquery datepicker doesn't work after ajax call if its already on page

  24. 24

    Click function doesn't work after ajax call in dynamic element (Backbone)

  25. 25

    Click function doesn't work after ajax call in dynamic element (Backbone)

  26. 26

    Function call doesn't display cout

  27. 27

    Rails 4 ajax flash messages cause strange behaviour for non xhr requests

  28. 28

    Rails 4 ajax flash messages cause strange behaviour for non xhr requests

  29. 29

    Ajax Call Worked; Doesn't Work Anymore

HotTag

Archive