Fragmented Thought

Coldfusion Redirect & Location with Session data

By

Published:

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

Let's say you have a form that handles products.

If someone shows up to the form without an ?id=##, you're sure they must mean to create one. If there is an id, they mean to update. In the end though, all the user cares about is the "Save" button. "Create" and "Update" are your job to worry about. So you've created a wonderful cfc that does the work on the form, sets a message about the result in the session, and want to display it.

You can't simply reload the page after creating the product, your page needs the newly created product's id in the url, and that breaks the back button. So, you try cflocation, and figure on outputting the message there. No dice. The message you put in the session is gone when you get there. That is because when you do cflocation, the cookie that carries session information to the client is never sent along to them. Cookies have to be sent back to the user, and cflocation is a server side redirect. So instead, you use this trick:

<cfset variables.url = cgi.script_filename & '?id=' & product.id> <cfheader statuscode="301" statustext="Moved permanently"> <cfheader name="Location" value="#variables.url#"> <cfabort>

Note that you must include the cfabort in your code. While the user is correctly redirected using the cfheader, the page it sits on finishes processing!