jQuery non-AJAX POST

Tidied Darin’s excellent solution slightly.

function myFunction(action, method, input) {
    'use strict';
    var form;
    form = $('<form />', {
        action: action,
        method: method,
        style: 'display: none;'
    });
    if (typeof input !== 'undefined' && input !== null) {
        $.each(input, function (name, value) {
            $('<input />', {
                type: 'hidden',
                name: name,
                value: value
            }).appendTo(form);
        });
    }
    form.appendTo('body').submit();
}

This is JSLint-compatible and makes sure that no form is displayed at the end of body tag despite possible css definitions. The usage is also slightly more straightforward, e.g:

myFunction('/path/to/my/site/', 'post', {
    id: 1,
    quote: 'Quidquid Latine dictum sit altum videtur'
});

Leave a Comment