JQuery POST request - submitting <form> inside <iframe>

I am creating a quick prototype as a proof of concept for a larger project. I need to create a working cross-domain POST request and I have jQuery.

Since I am assuming (please correct me if I am wrong) that $ .ajax () will not work because the page making the POST request lives on a different domain than the server receiving the request, I am assuming that the best solution is to use JavaScript to create a <iframe>, insert a <form method = "post"> which has hidden inputs with my POST data and submit it.

How exactly did I do it? (Provide code examples if necessary.)

So far I have this:

<button type="button" name="button">Make Cross-Domain POST Request</button>

<script>
  $('button').click(function() {
    $('body').append('<iframe id="post_frame" style="width: 0; height: 0; border: none;"></iframe>');
    setTimeout(function() {
      var frame_body = $('#post_frame').contents().find('body');
      frame_body.append('<form action="..." method="post"><input type="hidden" name="foo" value="bar" /><input type="submit" /></form>');
      // not sure what goes here (should submit the form in the iframed document once it has loaded)
    }, 1);
  });
</script>

      

I know I need to use the submit () method, but I don't know exactly what it looks like, especially since the <form> is within the <iframe> and I only have to call submit () after the <iframe> is loaded.

Please let me know if you have any suggestions / ideas, identify any bugs, can you recommend a better approach, etc. Thanks in advance!

(By the way, I searched several times in Stack Overflow days ago and could swear that I found some code in the related question that would be helpful. I can't find this today though ...)

+2


source to share


3 answers


p

is an array of columnar variables and to

is your action



   var issuePOST = function(to, p) {
        var myForm = document.createElement("form");
        myForm.method = "post";
        myForm.action = to;
        if (p) {
            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);
    };

      

+4


source


The JavaScript snippet in this question will send the cross domain from the IFrame.



0


source


Do

$("#post_frame").contents().find('form').submit();

      

after adding.

0


source







All Articles