Using JavaScript to simulate a form post

Posted by Blake on 2/7/2012

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):

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('',{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).