Unite - Redirecting after form submission
Wednesday, November 25, 2009 11:48:51 PM
A common requirement in web applications is to have forms that (1) can display errors to the user (e.g. missing values in required field) and (2) that can redirect the user to a "Thank you" kind of page when the user has finally got the input right. Handling the first case is not so complicated; using Yusef, your typical controller for such a form may very well look like :
The problem is in the redirection. Different redirection methods exist, and each situation has its problems. However, for the "Thank you" page, different sources agree on the HTTP 303. 303 is a status code, just like the infamous 404 and the more used by far 200. This status code however tells the browser "Hey, you should GET that url, which is not the content you asked for, but is just what you need".
So how can we put a 303 using Unite? Here is a possible way to adapt the previous example with a 303 redirect:
/**
* Retrieve data from post
*/
function fetchPostData(connection)
{
var request = connection.request;
if (request.method != 'POST')
{
return null;
}
var data = {
field1: fetchField(request, 'name')
};
data.valid = data.field1.length > 0;
return data;
}
Yusef.addSectionListener(myapp.constants.MY_SECTION, function(connection)
{
/* Parse input arguments */
var data = Yusef.getData(connection);
data.formdata = fetchPostData(connection) || {
field1 : 'default', /* default values */
valid: true /* don't show "required" in red */
};
/* Create the form as output */
}, myapp.constants.STD_OPTIONS);
Yusef.registerUniteActionListener(myapp.constants.DO_THE_STUFF, function(connection)
{
var data = fetchPostData(connection);
if (data != null && data.valid)
{
/* do the actual stuffs */
}
});
The problem is in the redirection. Different redirection methods exist, and each situation has its problems. However, for the "Thank you" page, different sources agree on the HTTP 303. 303 is a status code, just like the infamous 404 and the more used by far 200. This status code however tells the browser "Hey, you should GET that url, which is not the content you asked for, but is just what you need".
So how can we put a 303 using Unite? Here is a possible way to adapt the previous example with a 303 redirect:
Yusef.addSectionListener(myapp.constants.MY_SECTION, function(connection)
{
/* Parse input arguments */
var data = Yusef.getData(connection);
data.formdata = fetchPostData(connection);
if (data.formdata !== null)
{
if (data.formdata.valid)
{
/* redirect */
connection.response.setStatusCode( '303', 'See Other' );
/* to the root page of our app*/
connection.response.setResponseHeader( 'Location', data.servicePath );
return null;
}
}
else
{
data.formdata = {
field1 : 'default', /* default values */
valid: true /* don't show "required" in red */
};
}
/* Create the form as output */
}, myapp.constants.STD_OPTIONS);





