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

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.

Related

Can I use both onclick events and submit functionality on a form's submit button?

I am confused about some behaviour on my webpage where I use both submit action and onclick event on the Save-button in a form. It works fine for me, but it seems that some users have trouble to save the information in the form.
I have simplified the form here:
<div class="container">
<form id="myform" action="action.php">
<input "nameinput" type="text" name="name">
<button id="savebutton" type="submit" >Save</button>
</form>
</div>
Now... I have also added an jQuery section that shall hide the form when the save button is pressed:
$(".container").on("click", "#savebutton", function(){
$("#myform").slideUp("slow", function() {
$(this).remove();
});
});
So: When the user presses the Save-button it shall both send the name to action.php and trigger the click-event to close the form.
This works perfectly fine for me, but I wonder if this design can cause troubles on some browsers, especially older ones? I have got bug reports from users where the form is closed, but no data is saved (i.e. action.php isn't called). Is it possible that the form "dissapears" before the form can submit the data?
Here the default behavior of the submit button is to send the data to action.php. Definitely, it is going to load the page again when users click the submit button in that case your javascript code will not run.
I will recommend you to use JQUERY AJAX Documentation

javascript call before submit using thymeleaf does not work as expected

I am new to javascript so it might be a simple question for many.
I have used form sumbit in thymeleaf and am trying to add a JS validation before the form is submitted to the spring mvc controller. I can perform these two actions separately (individual tasks). However I could not really make them work one after the other (js function and form submit). Submit action is triggered by a button inside the form.
<form th:action="#{/user/trigger}" th:object="${triggers}" method="post">
<input type="hidden" name="tradeDate" th:value="${trigger.id.tradeDate}">
<button type="submit" id="ignore" name="action" value="ignoreOrder" class="btn btn-primary btn-sm">Ignore</button>
</form>
The js function is like below:
$(".ignore").click(function() {
//do some processing;
return false;
});
So can someone can help me to rewrite this code which will first call the JS function and submit the form to the java spring mvc controller? Thanks in advance.
The issue with your approach is that after your java-script is validating the code, your html 'submit' button is submitting the form as they're executing one after another. You haven't done anything to prevent the form submission after the validation is getting failed.
To overcome this issue, what you can do is to submit the form through your JavaScript code manually only when your validation is successful.
So your code will look something like this -
1.) Changes in Html code, instead of creating the button type as 'submit', make it as a normal button and run your javascript validation function on its click -
<form th:action="#{/user/trigger}" th:object="${triggers}" id="myForm" method="post">
<input type="hidden" name="tradeDate" th:value="${trigger.id.tradeDate}">
<button type="button" id="ignore" name="action" onclick="myValidationFunction()" value="ignoreOrder" class="btn btn-primary btn-sm">Ignore</button>
</form>
2.) Changes in Javascript code, now after clicking on the above button your javascript validation function will execute and after the validation is successful submit the form manually using the form id, something like this -
function myValidationFunction(){
if( some_condition ){
//validation failed
return;
}
//validation success , when above mentioned if condition is false.
$("#myForm").submit(); // Submit the form
}
For more information about using submit in jquery, refer the official documentation -
https://api.jquery.com/submit/
for jquery, it return a list, so:
$('#search_form')[0].submit();

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

One submit button two event in Html

<button id="Submit" onclick= "write_task_content()"> Submit.</button>
I have this code written on my page for submit button. write_task_content() function is writing the activity of users into the file. I need to redirect to another page which is in another directory when same submit button being clicked.
for example:
Current path C:\xampp\htdocs\CC_real task\3GBCJUK5B10I32J9O2EJNNQ339GPKH.html where Submit is written. where write_task_content() function needs to be executed to save user activity and with the same button redirect to another page in the same window browser C:\xampp\htdocs\IA_real task\3RKALKFQG14FDCEAT1S123EW94A792.
How could I do that?
First create your submit button:
<form action="destination-page.html">
<input type="Submit" value="Submit" />
</form>
Then, in the <script>...</script>, attach an onsubmit event to the form either using javascript or jquery:
Javascript:
var form = document.getElementsByTagName('form')[0];
form.addEventListener('submit',write_task_content,false);
jQuery:
$(document).ready(
$('form').submit(write_task_content);
);
When the submit button is clicked, write_task_content() will execute first and then the browser will request destination-page.html.
After saving the details use
window.location = "http://www.example.com";
This redirects to another location.

How can I keep focus on a overlay popup after submitting a form?

I have an overlay popup with a form inside. The form has a button and a textbox (imagine something like the FB Like and Comment box). Every interaction with the form triggers a MySQL DB Insert called through a PHP function. The problem is that after having clicked on the button or commented (and pressing enter key on the keyboard), the overlay disappears and the main page is refreshed. I don't want this to happen and I want to keep the focus on the popup. How can I do that?
Here's some code:
<div id="LikeAndComment">
<form name="formLAC" method="post" action="">
<div id="containerLike">
<button type="submit" id="likeit" value="FALSE" onClick="{vote(); keepFocus();}">
<img src="images/implike_BUTTON.jpg" "/>
</button>
</div>
<div id="containerComment">
Commenta: <input type="text" class="input" id="comment" onkeydown="if (event.keyCode == 13) { this.form.submit(); keepfocus(); return false; }"></input>
</div>
</form>
</div>
And here's the code of the keepFocus function:
function keepFocus() {
$('.formLAC').focus();
};
When you submit form as default without prevent form submit and using ajax, The browser will generate a new request and redirct you to the action url that you defined.
What you ask is to submit the form without redirect the page.
The ideal solution is to use ajax.
You can catch the submit-form event and prevent the default action.
then you have to handle it with you own code, In this case the ajax function.
An example how to send form with ajax you can see on this post with nice answer:
link to how make form submit with ajax

Categories

Resources