6

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?

Giedrius
  • 8,048
  • 6
  • 46
  • 84
  • If the controller returns a redirect it doesn't matter for your form page if you post it using ajax I think, the page won't reload, you will just get different data back – Asciiom Aug 28 '12 at 07:41
  • 2
    http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit – nbrooks Aug 28 '12 at 07:44
  • @JeroenMoons - don't need ajax here, I just need solution for posting data with location change on browser, just like submitting regular post form. – Giedrius Aug 28 '12 at 07:49
  • @nbrooks - there is jquery version in your mentioned question, but comments say it has bugs. – Giedrius Aug 28 '12 at 07:53
  • 1
    @Giedrius Any specific reason for wanting to use jQuery as opposed to the native js answer (the accepted one) provided? It's simple enough to convert the accepted answer to use jQuery, but it only really saves you a few characters, and everything there should be cross-browser compatible. Need help with that? – nbrooks Aug 28 '12 at 07:55
  • @nbrooks - may be you're right, may be native js is good enough, just hoped that I overlooked something in jQuery, because it should be quite common thing. – Giedrius Aug 28 '12 at 07:59
  • @Giedrius No, there doesn't seem to be any built-in jQuery function for this, though I agree it seems like it should be a common use-case. – nbrooks Aug 28 '12 at 08:07

1 Answers1

4

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();
}
Community
  • 1
  • 1
nbrooks
  • 17,489
  • 5
  • 46
  • 61
  • 1
    thanks a lot . this is best solution I was looking for . And this anwer is from 2012 OMG . Now I can change my code to jquery. https://stackoverflow.com/a/67716628/1901693 – Aditya Yada May 27 '21 at 06:22