Thou Shalt Not Update on GET

Just ending a bug-fixing session of an ASP.Net project, we came across an interesting issue:

  • The customer wanted to avoid the “post again” message when pressing the browser’s back button (scenario sketched here)
  • The web application used templates file to inject HTML code into the pages as a means to allow localization and customization by the customer
  • Some of the post-back actions should be triggered by links or buttons contained in the template files
  • Posting by mechanisms of the ASP.Net framework and implementing the Post/Redirect/Get design pattern was therefore not possible
  • Manipulation of the web site’s shopping cart had therefore been implemented as links issuing GET requests

As a consequence, when you added a product and hit the Back button to view the product again, you added it once more to the shopping cart. Clearly, this is in violation of the accepted semantics of POST and GET requests:

In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered “safe”.

Not good, greetings from The Spider of Doom.

To avoid major reorganization and rewrites of the existing pages, I took a shortcut using Javascript:

function PostAndRedirect(baseurl, params) {
    type: "POST",
    url: baseurl + params,
    success: function (xhr) {            // Success
      window.location.href = baseurl;
    // If any AJAX errors, alert them
    error: function (xhr, ajaxOptions, thrownError) { 

The function PostAndRedirect takes as parameter the target (most likely current) URL and the parameters to be posted. The POST is executed using the jquery.ajax() method. If the POST is successful, the function redirects to the URL (i.e. using a GET request).

Using this function, the browser never adds the POST request to its history, and therefore would not re-post upon pressing the Back button.

To invoke the Javascript function, simply add a Javascript URL as href value:

<a href="javascript:PostAndRedirect('SomeUrl.aspx', 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: