Search code examples
ruby-on-rails-3jquerynotice

Using respond_with how can I flash a notice with an ajax response?


The flash method only shows the message after the page reloads... what do I do to get it to appear when I'm using :remote => true?


Solution

  • if you are using :remote => true you are actually doing Ajax request. in that case, the flash will not work.

    What you need is to have a js function that mimics that flash message.

    I usually have that: (Mootools, but you probably get the idea)

    showMessage: function(message, style, addReload)
        {
            var class_name = style + "_message message";
    
            var flash = $("flash_message");
    
            if (flash) {
                flash.dispose();
            }
    
            flashElement = new Element("div", {
                id: 'flash_message'
            });
            flashElement.set('class', class_name);
    
            var strong = new Element('strong', { 
                                    html: message
                                    });
    
            if(addReload)
            {
                strong.adopt(
                                new Element("a", {href: window.location, html: 'Reload'})
                            );
            }
    
            flashElement.adopt(
                                strong
                            );
    
    
            flashElement.inject($("mainPageContainer"));
            Site.show_message();
        },
    

    Whenever I use :remote => true, I have that in the js view

    <% flash.discard %>
    Dashboard.showMessage('Comment added and was sent to clients', 'notice');