Search code examples
grailsgroovycontrollergsp

Grails: Why are flash message only rendered after a refresh if you use ajax?


Here is the Problem: I have a remoteForm, which itself works fine. I debugged the controller and every command runs through. However if an Exception occures and I set a flash.error message. The message will only be displayed AFTER I manually press F5 (Refresh). I do not understand why the AJAX call works, but the flash messages are empty.

I have a remote form (in index.gsp):

       ...
         <g:formRemote name="remoteForm"
                      url="[ controller: 'document',
                       action: 'search']"
                       onLoading="showSpinner();"
                       update="searchBlock"
                       action="${createLink(controller: 'document', action:'search')}"
                       >

        <div class='info_message'>
            ${flash.message}
        </div>
        <div id="searchBlock">will be exchanged</div>
       ......

A controller:

    ......
        } catch (Exception e){
            log.error(e)
            flash.error = e.getMessage()
            flash.message="HINTTEST"
            render (template:'searchNoResult')
            return
        }
    .....

The template (of _searchNoResult) has the following content:

 <span>Sorry, your search yielded no result.</span>

  <g:if test='${flash.error}'>
        <div class='error_message'>
            Error: ${flash.error}
        </div>
    </g:if>
    <g:if test='${flash.messages}'>
        <div class='info_message'>
            Hint: ${flash.message}
        </div>
    </g:if>

Documentation says: the the flash scope lives through the current request and the call after that. If I use a normal form and submit everything works, but I want to use ajax and render templates, so I do not have to repeat code so often.

Edit 1 First the index.gsp is rendered. The remoteForm changes the seachBlock div with the template, which contains the flash.messages. They are not filled.

Grails Version 1.3.7 an upgrade is not possible at the moment.

Edit 2 The exception e, was not the Exception, which was original thrown by me. The message was null, which resulted in null for messages....


Solution

  • From the code you've shown nothing is updating the info_message div with a message when the ajax request returns a response. The formRemote is only updating the searchBlock element. If the page doesn't refresh the flash.message can't be rendered.