Paweł Laskowski Paweł Laskowski - 24 days ago 9
HTML Question

Fire iframe and submit form on the same button press

Spend good few hours on this one and couldn't find a good solution so here goes:

I am having a tracking pixel in an iframe. On button click I want to firstly fire the tracking pixel and then submit a form. Usually I would have a page in the middle where I fire a pixel and pass a form but in this project I have no access to the backend and cannot make intermediate page. I have tried to simply add onClick='firePixel()' to button assuming it will submit the form AND load iframe but it does not. I have also tried to create 2nd function and add callback in a way: onClick(firePixel(submitForm)) having submitForm as a callback - also with no luck.

P.S Also I have tried to have button outside of the form (as seen below) as well as inside the form - no luck.

Not sure what's the best practice here? I don't mind if iframe is being fired in the background - user is never seeing it - it's just a tracking pixel.

Please find code (which does not work) below:

<iframe id='conversioniFrame' data-src="testFrame.html"
src="about:blank" width='100px' height="100px">
<div class='panel clearfix'>
<form id="options-go-to-insurer" action="/life/buy/" method="post">
<!-- Form stuff -->
</form>
<button id="conversionButton" class="button primary expand apply-button" onclick="conversionFunction(submitForm())"><b>Apply Now</b></button>
</div>


<!-- STOP -->
<script>

function conversionFunction(callback) {
var iframe = $("#conversioniFrame");
iframe.attr("src", iframe.data("src"));
callback();
}

function submitForm() {
document.getElementById("options-go-to-insurer").submit();
}
</script>

Answer

Note the type="button" is mandatory to not submit the form

If the page and the iframe code is from the same domain, you could just return

<script>parent.document.getElementById("options-go-to-insure‌​r").submit()</script‌​>

from the testIframe.html

If not, try this

$(function() {
  $("#conversionButton").on("click", function() { // when button is clicked
    var $tracker = $("#conversioniFrame");
    $tracker.attr("src", $tracker.data("src")); // load the page
  });
  $("#conversioniFrame").on("load", function() { // when page has loaded
    $("#options-go-to-insurer").submit(); // submit the form
  });
});
<iframe id='conversioniFrame' data-src="testFrame.html" src="about:blank" width='100px' height="100px">
  <div class='panel clearfix'>
    <form id="options-go-to-insurer" action="/life/buy/" method="post">
      <!-- Form stuff -->
    </form>
    <button type="button" id="conversionButton" class="button primary expand apply-button"><b>Apply Now</b>
    </button>
  </div>

Comments