Using JavaScript to simulate a form post


I was recently updating a site that used jQuery extensively to talk to .Net based web services. The payment provider was changing and instead of being able to call them from a web service, I now how to post to their site after running some server side code on my side (which is problematic in a WebForms setup). I found a solution that worked great here (tested in IE9, FireFox 7.0.1 and Chrome 82 or whatever version they’re on right now):

http://mentaljetsam.wordpress.com/2008/06/02/using-javascript-to-post-data-between-pages/#comment-1212

For posterity, here is the function Peter Finch wrote:

function postwith (to,p) {
    var myForm = document.createElement("form");
    myForm.method="post" ;
    myForm.action = to ;
    for (var k in p) {
        var myInput = document.createElement("input") ;
        myInput.setAttribute("name", k) ;
        myInput.setAttribute("value", p[k]);
        myForm.appendChild(myInput) ;
    }
    document.body.appendChild(myForm) ;
    myForm.submit() ;
    document.body.removeChild(myForm) ;
}

To call this code, you’ll pass in the name of the page or url you want to post to and then a name value list of HTML elements in the form and their values:

    postwith('post.aspx',{user:'peter',cc:'aus'});
    postwith('http://www.yoursite.com/YourForm.aspx',{name:'John Doe',subject:'this is a test message',captcha:'br26942'});

Note, that when you call this from the JavaScript, it will post your page so any JavaScript after this will not execute. In my case, I made an Async jQuery call to the server, and when that call was done I made a form post using this (and so far, so good).

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.