Fire iframe and submit form on the same button press - javascript

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>

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>

Related

What is the proper way to submit a form with JS and still post all form data successfully?

I'm working with an embedded app on our dev site and when I click the submit button inside the iframe, I am triggering a manual submission event on another form (not in an iframe) on that page. If I manually click the submit button for the form, my data posts and everything works correctly. However, I want to eliminate an extra user click and submit the external form automatically when a user submits the other form inside the iframe.
I've got everything working correctly on a base level. When a user clicks the submit button in the iframe, I am using JQuery to grab values from inside the iframe and set values in this external form. Using the jquery 'submit()' event, I am then able to submit that external form. The problem is, the page refreshes and the data doesn't go anywhere. If I remove the 'submit()' event and manually click the submit button, the form posts and in this case, adds a product with custom data to the product cart.
As a proof of concept, this is my 'iframed' HTML.
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Proof of Concept</h1>
<p>Total cost: $<span id="cust_price">222.22</span> plus shipping.</p>
<p>Quote number: <span id="quot_num">1546751962211</p>
<form method="POST" enctype="multipart/form-data" id="newQuoteForm">
<button type="submit" class="btn btn-primary" name="new-app-btn">Add to Cart</button>
</form>
</body>
<footer>
</footer>
</html>
Here is my on-page form that is OUTSIDE the iFrame.
<form method="POST" enctype="multipart/form-data" id="outer-quote-form" action="/checkout/">
<label class="quote_number">Quote Number:
<input type="text" id="quote_number" name="quote_number" value="">
</label>
<label class="custom_price">price:
<input type="text" id="custom_price" name="custom_price" value="">
</label>
<button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
</form>
Then, I have JQuery working to grab the iframed values and puts them in the exterior form. Afterwards, it fires a 'submit()' event on that form.
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("#outer-quote-form").submit();
return true; //return false prevents submit
});
});
</script>
Except when the jquery submit() event fires, the form appears to submit and the page refreshes but no data is posting as it does when I manually submit the form. Is there an extra step here or a better way to fire the form submit with post data?
Edit: Adding the PHP function that isn't firing on jquery submit() for context.
if (isset($_POST['ws-add-to-cart'])) {
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
global $woocommerce;
global $product;
$product_id = 138;
$woocommerce->cart->add_to_cart($product_id);
}
header("Location:https://www.devsite.com/checkout/");
}
The reason for the form not submitting because you are submitting the whole form without the submit button which is <button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button> which you have declared in php to get a post request like this
if (isset($_POST['ws-add-to-cart'])) {...
When you call submit(); on the form via the get method, you see '/new-quote/?quote_number=1546751962211&custom_price=222.22'
but where's ws-add-to-cart, it's not submitting and that's the reason why php isn't getting your request
The fix will be to add .click() on the submit button instead of submitting the form
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementsByName("ws-add-to-cart").click();
}
</script>
Or in your script in case you want to use jquery, this is the fix
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("button[name=ws-add-to-cart]").click();
return true; //return false prevents submit
});
});
</script>
This is definitely the answer and sorry for my stupidity, i didn't pay required attention before
try removing return true from your js code
if that doesn't work, try changing the <form method="POST" to <form method="GET" to debug the values in the url just for checking that the form actually fires up with values
Alternative method: Old school method
code for page OUTSIDE the Iframe
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementById("outer-quote-form").submit();
}
</script>
code for the Iframe file
<script type="text/javascript">
$('#newQuoteForm').on('submit', function(event) {
var Page = window.parent;
var allVals = {
price:$('#cust_price').text(),
num:$('#quot_num').text()
}
Page.enterVals(allVals);
event.preventDefault();
});
</script>
Explanation
window.parent refers to the parent window where the iframe is loaded on, with reference to this we can trigger functions that are in the parent window so by this, we created a variable and added the information which is sent by the function enterVals() to the window
The enterVals() function just puts the values and submits the form without any jQuery.
What is the proper way to submit a form with JS?
This might not be the 'best' way to submit a form with js but is cross-browser which is good

using window.open() has the effect of submitting form prematurely

I have a web-form written in ASp.Net MVC5 which is used to gather some details from the user. However, before I get them to submit the form, I want them to have the option to look at another web-page (in a new window or tab) which gives them more information if they need it prior to submitting the page. To that end, on the web-form, I have a form with the following buttons:
<form action="/Application/MyAction" method="post" id="myForm">
// various fields ...
<button onclick="getMoreInfo()">More Information</button>
<button type="button">Submit Form</button>
</form>
Then, at the bottom of the page I have the following javascript defined:
<script>
function getMoreInfo()
{
var urlToUse = 'http://some-other-page.html';
window.open(urlToUse);
return false; // trying to stop the form submission from occurring
}
</script>
My problem is that when this "More Information" button is clicked, it has the effect of submitting the form [which I don't want to do yet] - since there is a separate submit button for doing that task. Is there a way to use a button to jump to another page without actually submitting the current form?
thanks heaps,
David.
I found that answer #3 at this question helped me:
How do I cancel form submission in submit button onclick event?
My solution was to change the code thus:
I changed the button code to look like this:
<form action="/Application/MyAction" method="post" id="myForm">
// various fields ...
<button id="moreInformationButton" >More Information</button>
<button type="button">Submit Form</button>
</form>
And then I changed the javascript to look like this:
$("#moreInformationButton").click(function (event) {
event.preventDefault(); // This stops the submit form being triggered
var urlToUse = 'http://some-other-page.html';
window.open(urlToUse); // open the help page
});
This allowed me to open up another window or tab with more information without actually submitting the form.

capture submit event with dynamically added content with JavaScript

I am building a sort of page builder where the user can add blocks to the page and then save the layout. I have encountered a problem that I can't seem to figure out. I have a form that is dynamically added to the page with JavaScript containing a file input as so:
<form class="upload " action="" method="post">
<input id="" type="file" class="fill" name="upload">
<img src="/admin/img/default.png" alt="">
</form>
After adding the content I call the following function to add event listeners. $el corresponds to the file input.
function changeListen($el){
$el.addEventListener('change', function(){
$el.parentElement.submit();
});
$el.parentElement.addEventListener('submit', function(e){
e.preventDefault;
// call Ajax request...
});
}
I want to be able to update the database with an Ajax request when an image is selected, therefore I submit the form within the change event, so far so good, but for some reason the submit event is not taken into account and the page reloads. Any solutions or workaround appreciated, preferably not jQuery.
By using onsubmit event in HTML, you can call javascript function this way and do ajax calls.
Javascript sample
<script>
function doSomething() {
alert('Hello, World');
return false;
}
</script>
HTML Sample
<form onsubmit="return doSomething();">
<input type="submit" value="Submit" />
</form>
EDIT: return false in javascript so ? does not appear in URI after clicked

refresh url in iframe after a submit button of another form is clicked &formatting url contents inside iframe

How can I reload an iframe which is already "rendered" due onload call through a javascript.
I have a page where I can add new users (by clicking submit button after entering name).
The page also displays all available users in an iframe(during onload, the iframe is "preloaded" with users). Everytime I add a new user and click on submit, the iframe(list) should also fetch the updated list automatically.
Also I am wondering how I can format the URL "get" results in the hidden form.
Can a URL copied into an iframe be modified at the destination?
How can I do this? Please help!
This is what I have so far:
<html>
<head><title>welcome page</title>
</head>
<body onLoad ="subMe()">
<script>
function subMe(){
document.getElementsByTagName('form')[1].submit();
}
function OnButton2()
{
document.getElementById("myframe").src ='http://localhost:8000/getusers/' ;
}
</script>
<div align="center">
<h1>Home</h1>
<form name ="Form0" action= "/cgi-bin/myuser.cgi" method ="get" target="uframe" onsubmit="return OnButton2();">
Enter Name:<input type="text" id ="name" name="name">
<input type="submit" value="Create new User">
</form>
<iframe id="uframe" name="uframe"></iframe>
<br>
<div style="display: hidden;">
<form action="http://localhost:8000/getusers/" method="get" target="myframe">
</form>
</div>
<iframe id="myframe" name="myframe"></iframe>
</div>
</body>
The answer is definitely as others have commented:
document.getElementById("myFrame").src = "http://www.google.com/"
There are a few reasons why this may not work. The most likely is that JS "same origin" policy is being violated. Try setting the src to a relative url like "getusers/" and watch for console errors.
Try also calling OnButton2() on its own and see if you can narrow down the problem.
Additionally, It sounds a lot like you are trying to load data into the DOM without reloading the page. Have you tried using AJAX? it's very simple and powerful once you get the hang of using it and will allow you to submit a form and display results in any format you wish, without using iframes or reloading the page.

Html page onLoad calling javascript without submit button

i am trying to load a html page with the results of a "get" from another link.The idea is when I open the page, I should see the results of the get displayed.
I tried the following with javascript but with no success. The problem is I always get a submit button on the page. I want the submit to be "pre" done!
Please help. Here is what I have:
<body onLoad ="subMe()">
<script>
function subMe(){
document.getElementById("formButton").submit();
}
</script>
<div align="center">
<div style="display: hidden;">
<form action="http://localhost:8000/getusers/" method="get">
<input type="submit" id="formButton" />
</form>
</div>
..
</body>
Any idea? This is linked to my previous post:Cgi C program return value to main HTML and display result
The problem is that you are submitting a button, not the form.
Try:
function subMe() {
document.getElementsByTagName('form')[0].submit();
}
Since you have no need for the submit button, there is also no harm in removing it from the html.
I believe that you have to submit the form, not the button.
document.getElementsByTagName('form')[0].submit();
submit() should be called on the form element, not on a submit button.

Categories

Resources