Submitting form data to a popup window for processing - javascript

As so many posts start: This might be a duplicate, but...
Here's what I'm trying to do:
Have an HTML page within my site that contains a FORM element with various input, etc. elements inside, e.g.:
<form id="form1" method="post" action="">
Name: <input type="text" id="text1" size=10><br>
<input type="hidden" id="hidden1" value="This text is hidden">
<input type="checkbox" id="checkbox1" value="Y"> Include stuff?<br>
Job Title: <select name="select1" id="select1">
<option value="1">President</option>
<option value="2">Chief Cook</option>
<option value="3">Bottle Washer</option>
</select>
<button name="button1" id="button1" onclick="doThisScript()">Submit Stuff</button>
</form>
I want the "doThisScript" function to open a new popup window with coded parameters, directed to a url on our site, and pass the form's values to that url, something like:
function doThisScript() {
var form1=document.getElementById('form1');
form1.onsubmit=function() {
var w=window.open('resultsprogram.asp','resultswin','toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=300');
this.target = 'resultswin';
form1.submit();
}
}
This code (based on the closest Q/A here I could find) transfers the form from the "base" page to the popup window. But what I'm trying to do, I guess, is submit the form back to the server but have the results come back to that popup window instead of either the base page or a new tab/standard browser window.
Is that even possible? I assumed there had to be a way to create the popupwin with a URL, pass that page the current form values, and tell that popupwin to itself submit the form so that it, not the base page, gets the results. Doable?

Calling window.open() will invoke the server script, but it won't send the form parameters to it.
You need to change the form's action to be the server script:
function doThisScript() {
var form1=document.getElementById('form1');
form1.action = 'resultprogram.asp';
form1.target = 'resultswin';
}
}
You don't need to call submit() explicitly, since that's the default action of clicking on the submit button.

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

Changing input value of a form and submitting with jQuery

I have the following HTML code:
<html>
<!-- assume jquery is loaded -->
<body>
<form id="sform" method="get" style="display:none;">
<input type="hidden" name="eid" />
<input type="hidden" name="returnURL" />
<input type="hidden" name="returnID" value="ieid" />
<select id="dropdownlist" name="ieid">
<option selected="selected"></option>
</select>
</form>
</body>
</html>
What happens is the user enters an email address, it checks (server-side with PHP) the credentials and if valid, returns the following JSON object (in this case, assume that the values are valid urls (ie. http://sitehere.com/somethingelse):
{
"get_action" : "geturl",
"eid" : "eidurl",
"return_url" : "returnurl",
"option_url" : "optionurl"
}
This is retrieved when the user hits the login button on the home page. This button triggers a POST request which retrieves the results and parses the JSON into the form above. I then change the values of the form from the original code and the action of the form itself before submitting the form. This is shown below.
$.post('/?c=controller&a=method', {'email' : $('input[name="email"]').val() }, function(data){
var result = $.parseJSON(data);
$('#sform').change_action(result.get_action);
$('input[name="eid"]').change_val(result.eid);
$('input[name="returnURL"]').change_val(result.return_url);
$('select[name="ieid"]').find('option:selected').change_val(result.option_url);
$('#sform').submit();
};
Where change_val() and change_action() are defined like this:
$.fn.change_val = function(v){
return $(this).val(v).trigger("change");
}
$.fn.change_action = function(v){
return $(this).attr('action', v).trigger("change");
}
The reason why I defined these functions was because originally, I had just been calling val('new value'); and the form seemed to not be updating at all. I read that I had to trigger a change when using jQuery to update the form before submitting it.
However, even after triggering a change, it seems like the HTML still isn't updated (at least in Chrome) and the form is not being submitted correctly because none of the values are actually changing.
So, I need to be able to take a parsed result, update the values in the form (with specific id's), and then submit the form so that it re-directs somewhere. Is there a way to do this correctly?

How to send only POST-data (via Button click) in webView without following link

I load a webpage in a webView. In onPageFinished(..) i run some javascript code, which finally clicks a submit button. So the webView sends Post data and get an answer and loads a new page. That works fine, but i dont need the new page, its just unnecessary network load. I only need to submit the data.
So is it possible to send only the submit without loading the new page? I know that i can send post data with HTTPConnection, but i dont know the header consistence exactly, so i cant set the params. Is there any possibility with JS/Webview to abort?
Edit: I cant override onPageStarted() in my WebViewClient and perform a view.stopLoading(), because the new URL is still the same. But the site appearance is quite different. So i have to stop loading before
HTML of the submit button:
<input type="submit" name="savechanges" class="btn btn-primary" value="Speichern">
and three aditional lines above
<input type="hidden" name="uid" value="390">
<input type="hidden" name="option" value="com_jevents">
<input type="hidden" name="task" value="dash.listprojects">
which meaning i dont know (site is made by Joomla)
You can simply create a "virtual form" and submit it, like:
var $form = $("");
... on click:
$form.submit();
Hope this helps
Ops its removing my html from inside $form, inside the jQuery selector there should be a form like "form method='post' action='{someurl}'" with angle braces opening and closing properly

Multiple form submit with one Submit button

I have two forms. I want to submit both forms with 1 button. Is there any method that can help me do it?
Example:
<form method="post" action="">
<input type="text" name="something">
</form>
<form method="post" action="">
<input type="text" name="something">
<input type="submit" value="submit" name="submit">
</form>
I want both forms to be submitted with 1 submit button. Any help would be appreciated.
The problem here is that when you submit a form, the current page is stopped. Any activity on the page is stopped. So, as soon as you click "submit" for a form or use JavaScript to submit the form, the page is history. You cannot continue to submit another page.
A simplistic solution is to keep the current page active by having the form's submission load in a new window or tab. When that happens, the current page remains active. So, you can easily have two forms, each opening in a window. This is done with the target attribute. Use something unique for each one:
<form action='' method='post' target='_blank1'>
The target is the window or tab to use. There shouldn't be one named "_blank1", so it will open in a new window. Now, you can use JavaScript to submit both forms. To do so, you need to give each a unique ID:
<form id='myform1' action='' method='post' target='_blank1'>
That is one form. The other needs another ID. You can make a submit button of type button (not submit) that fires off JavaScript on click:
<submit type='button' onclick="document.getElementById('myform1').submit();document.getElementById('myform2').submit();" value='Click to Submit Both Forms'>
When you click the button, JavaScript submits both forms. The results open in new windows. A bit annoying, but it does what you specifically asked for. I wouldn't do that at all. There are two better solutions.
The easiest is to make one form, not two:
<form action='' method='post'>
<input type='text' name='text1'>
<input type='text' name='text2'>
<input type='submit' value='Submit'>
</form>
You can place a lot of HTML between the form tags, so the input boxes don't need to be close together on the page.
The second, harder, solution is to use Ajax. The example is certainly more complicated than you are prepared to handle. So, I suggest simply using one form instead of two.
Note: After I submitted this, Nicholas D submitted an Ajax solution. If you simply cannot use one form, use his Ajax solution.
You have to do something like that :
button :
<div id="button1">
<button>My click text</button>
</div>
js
<script>
$('#button1').click(function(){
form1 = $('#idIFirstForm');
form2 = $('#idISecondForm');
$.ajax({
type: "POST",
url: form1.attr('action'),
data: form1.serialize(),
success: function( response ) {
console.log( response );
}
});
$.ajax({
type: "POST",
url: form2.attr('action'),
data: form2.serialize(),
success: function( response2 ) {
console.log( response2 );
}
});
});
</script>
You could create a pseudo form in the background. No time to write the code, jsut the theory. After clicking submit just stop propagation of all other events and gather all the informations you need into one other form you append to document (newly created via jquery) then you can submit the third form where all the necesary infos are.
Without getting into why you want to use only 1 button for 2 forms being submitted at the same time, these tools that will get the input data available for use elsewhere:
Option 1...
Instead of using <form> - collect the data with the usual Input syntax.
ex: <input type="text" name="dcity" placeholder="City" />
Instead of using the form as in this example:
<form class="contact" method="post" action="cheque.php" name="pp" id="pp">
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button class="button" type="submit" id="submit">Do It Now</button>
</form>
use:
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button type="button" onclick="CmpProc();" style="border:none;"><img src="yourimage.png"/> Do It Now</button>
Then code the function CmpProc() to handle the processing/submittion.
Inside that function use the Javascript form object with the submit() method as in...
<script type="text/javascript">
function submitform() {
document.xxxyourformname.submit();
}
</script>
Somehow I suspect making the two forms into one for the POST / GET is worth reconsidering.
Option 2...
Instead of POST to use the data to the next page consider using PHP's $_SESSION to store each of your entries for use across your multiple pages. (Remember to use the session_start(); at the start of each page you are storing or retrieving the variables from so the Global aspect is available on the page) Also less work.
Look man. This is not possible with only HTML. weither you gether the inputs in one form or else you use jquery to handle this for you.

Submit Form that is Dynamicly inserted into the page using jQuery and AJAX?

I have a Form that is generated with JavaScript and then inserted into a popup Modal window.
My form HTML is not generated or inserted into the page until well after the DOM has generated the whole page (it is triggered from a Socket post event which then makes my popup open and inserts the HTML for this form)
There can also be multiple Forms inserted into the page so not just 1.
Here is an example of the form code that is generated and inserted into the page...
<form action="/" id="logCallForm" class="logCallForm">
<div class="col-xs-10">
<input class="form-control input-sm" type="text" name="subject" placeholder="Subject">
<br><input type="hidden" name="qmsId" value="1c885762-27d5-58ef-9f95-527ae750c9be">
<input type="hidden" name="dateTime" value="2013-11-07 01:05:19">
</div>
<input type="submit" value="Save Call">
</form>
Now below is some JavaScript that is already running on the same page, my goal is to be able to POST these Forms using AJAX. Right now it does not seem to detect the code though as when I hit the submit button, it loads a new page instead of trying to submit through AJAX.
Please help me? I am pretty sure it has something to do with my Forms being added after the page has been loaded already?
$(function () {
$('.logCallForm').on('submit', function (e) {
var url = '/custom/modules/nam_call_logger/call_server.php';
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), // serializes the form's elements.
// qmsId dateTime subject
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault();
});
});
Try subscribing in a lively manner:
$(document).on('submit', '.logCallForm', function (e) {
Basically this will subscribe to the submit event of elements that match the selector, even if those elements do not yet exist at the time you are making the subscription (a.k.a the DOM load of the page). It will listen for future elements that might be added to the DOM and which match the selector.

Categories

Resources