Kurama
Kurama

Reputation: 629

How to show flash on a page I get redirected if rediction is performed on a client?

I send an ajax request on page1 and when I return a response, I do a redirect on a client via javascript on page2. What I want is to show a flash on a page2. Just "put_flash("something")" doesn't work because I can only call it from an action I return an ajax response from on page1. Whereas I want to show flash on page2 where I get redirected by javascript code. How can I do that?

Upvotes: 1

Views: 305

Answers (1)

Topher Hunt
Topher Hunt

Reputation: 4804

My understanding of how flash works (mainly from the Rails world, but I had no reason to think Phoenix handled it differently) is this:

  • Your flash message is included in a rendered response. Usually this response is a redirect (302 etc.), but it can be any status code and any response body.
  • The flash is just a cookie-based instruction that the client should send along with the next request, to display a certain message in the following rendered response (usually HTML).
  • These mechanics should work exactly the same regardless of whether the initial response is a 302 redirect, or some JS code that triggers a page refresh at some point -- or even if the response is just a normal HTML page containing a "Refresh me!" link, etc. Regardless of how the next request is triggered, that next request should include the flash cookie and you can set up the response to display the flash message accordingly.

Note: If the subsequent request to the server is an AJAX request that returns JSON, I don't know exactly what will happen to the flash content in this case. My guess is that when constructing your JSON response, you can check the flash and include a message if present, just like you do when constructing an HTML response.

Upvotes: 1

Related Questions