moar articles
Tweet
Follow @nicferrier

Javascript Form processing

This is another of those I've wanted to do this for ages why I haven't I done it yet type posts.

I've always been unhappy with HTML Forms, they seem easy but to me they never are, I get caught up in all the ways I could solve the problem of declarative vs dynamic programming.

For a while I've thought that a decent form library was all that was needed, a few routines for abstracting enough bits of it that the problem becomes simpler (at least in Javascript, FORMs working without javascript is a complete, huge, other problem).

As far as I'm aware though, no one has written a decent little form library. I am surprised there is not more support in jQuery, for example. There is a lot jQuery will let you do... but some key things that it won't.

One of the things that it doesn't do is add abstraction for form processing so you can totally ajax it; that is: add a javascript event handler to the form and have it take over the processing of the form. jQuery does have tools to let you do some of this:

But these are very low level parts of what I often want to do with FORMs, which is something like this:

So I finally wrote the code for doing this. Here it is:

var form_queue = new Array();

var form_queue_process = function (form_queue) {
    var head = form_queue.shift();
    while (!(head === undefined)) {
        var action = head[0];
        var data = head[1];
        var cb = head[2];
        $.post(
            action, data,
            function () { if ($.isFunction(cb)) { cb(); } }
        );
        head = form_queue.shift();
    }
};

var form_attach = function (selector, callback) {
    var action = $(selector).attr("action");
    $(selector).submit(
        function (evt) {
            var data = $(evt.target).serialize();
            $(evt.target)[0].reset();
            form_queue.push([action, data, callback]);
            form_queue_process(form_queue);
            return false;
        }
    );
};

This is the meat of the code, you can use it with jQuery, to attach a FORM selector, for example:

form_attach(".channel-send");

So any FORM matching that selector will be attached to the queuing handler. The queue doesn't care what the source form is, but it does offer the completion callback so a FORM could get an update when something happens.

This stuff is so generic it should really be offered by a library I think. I guess I'll look to offer it to jQuery or make a plugin or something. Do let me know what you think.