A refactoring from the trenches

A little earlier this week I came across this JavaScript function while visiting some code in the application I’m working on:

 

function filter_form(form) {

    var form = jQuery(form);

    var action = form[0].action;

 

    //get the serialized form data

    var serializedform = form.serialize();

  

    //redirect

    location.href = action + "?" + serializedform;

}

 

The function takes a form, serializes it, and adds its values to the URL, and redirects to it. I found the need to do this is a little odd, so I had a look at the calling code:

 

<form action="<%= Url.Action<SomeController>(x => x.FilterAction()) %>"

method="post" 

class="form-filter">

 

       <%–some input fields here–%>

 

        <a href="#" onclick="var form = jQuery(this).closest(‘.form-filter’); filter_form(form); return false;"

        title="Filter this"

        class="ui-button ui-state-default" 

        id="filter-form"

        rel="filter">Go</a>

 

</form>

 

The exhibited behaviour is that clicking the link (styled as a button) will cause a redirect to the target page with the addition of some query parameters.

Although we can see the developers intent (providing filters as part of the query string), the implementation leaves a lot to be desired.

Let’s see if we can do better.

 

We have a couple of clues here already; the form represents “search filters” and so is idempotent (i.e., causes no side effects).

 

Instead of a JavaScript driven redirect, why not submit the form using HTTP get:

get: With the HTTP "get" method, the form data set is appended to the URI specified by the action attribute (with a question-mark ("?") as separator) and this new URI is sent to the processing agent.

 

<form action="<%= Url.Action<SomeController>(x => x.FilterAction()) %>" method="get">

       <%–some input fields here–%>

<button title="Filter this" type="submit" value="Go">Go</button>

</form>

 

This way we get the same behaviour, minus the unnecessary JavaScript.

About craigcav

Craig Cavalier works as a Software Developer for Liquid Frameworks in Houston Tx, developing field ticketing and job management solutions for industrial field service companies.

Posted on April 12, 2011, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a comment