Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the shortest way to create post form and submit it using jQuery? [duplicate]

Tags:

jquery

I have a button with attributes data-url and data-parameter and need to post that to controller. Thing is, that controller will return a redirect, so $.post not really helpful here, I'm thinking about creating form on the fly and submitting it.
I think that is quite common task, but I couldn't find any shortcut on jQuery to do this, what would be the shortest/best way to do it?

like image 431
Giedrius Avatar asked Aug 28 '12 07:08

Giedrius


1 Answers

Source: https://stackoverflow.com/a/133997/803925

Modified to use jQuery:

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    var $form = $("<form>")
        .attr("method", method)
        .attr("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var $hiddenField = $("<input type='hidden' >")
                .attr("name", key)
                .val( params[key] );

            $form.append( $hiddenField );
         }
    }

    $('body').append( $form );
    $form.submit();
}
like image 139
nbrooks Avatar answered Oct 11 '22 04:10

nbrooks