I want to submit my form via Ajax. I have done it before but for some reason whenever I click submit it will always submit the form and refresh the page. I made a test function just to console log once submit button is pressed but that doesn't even work.
Once I can get the console log working without page refreshing then I can do the Ajax myself since I know how.
Here is my form (keep in mind Im only going to post one input here just for an example).
function submit_form(e) {
e.preventDefault();
console.log('working');
return false;
};
{!! form_open('myaccount/product_coupon/add',['id' => 'product_coupon_form', 'onsubmit'=> 'submit_form']) !!}
Username <input type="text" name="username" class="form-control">
<input type="submit" class="btn btn-primary" id="submit">
</form>
I have also tried in javascript calling it by $('#submit').click(function()... but that still did nothing
1st: be sure you include jquery
2nd: wrap your code in $(document).ready(function(){ //code here })
3rd: you can use form submit instead of submit button click
$(document).ready(function(){
$('#product_coupon_form').on('submit' , function(e){
submit_form(e);
})
});
Related
I am trying to prevent a form submission from happening using the event.preventDefault() in JS. While this works fine on a standard form submission, it seems to not be stopping the submission when the form is submitted externally by JS.
Here is an example HTML form that I am using:
<form id="demo12" method="post">
<input type="hidden" id="testID" name="testID" value="42">
</form>
Click this sentence to submit the form
And here is the included javascript/jquery file that is trying to catch this form being submitted:
$("[id^='demo']").submit(function (event) {
event.preventDefault();
// Then there is some ajax code here
}
Due to the nature of the form being added in through Jinja, there are multiple similar forms. I want to catch any form that starts with 'demo' in the id field and run some AJAX to fetch some new information from the server.
This has worked for me in the past, but the only difference is instead of there being a submit button, the form is being submitted separately through an html hyperlink tag. Is JQuery not able to catch the event of the form submission when it is submitted like this?
Currently when I do this, it just posts the form to the same html page and it the jquery function never occurred. I do see in debugging, through in the browser, that the jquery is listening properly and recognizes the form as something it is listening for to be submitted.
$('[data-submit]').on('click', e => {
$(e.target.dataset.submit).trigger('submit');
});
$('#demo12').on('submit', e => {
console.log('you submitted me!');
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="demo12" method="post">
<input type="hidden" id="testID" name="testID" value="42">
</form>
Click this sentence to submit the form
Rather than calling the native submit event, trigger the submit event on the form. This way, you can process it and conditionally cancel it.
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();
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
Can we run a js function on a submit button and php on the same button. I have a submit button that sends form data to a database using php, but I want a second action (JavaScript function) to take place once the button is clicked as well. Is that possible?
You can add onclick() event to submit button. it will execute before submitting the form.
var buttonClick = () => {
alert("Do what you want to do!"); // Add your second work here
}
<form action="yourfile.php">
<input type="submit" onclick="buttonClick();">
</form>
The correct method is to call the javascript function on the onsubmit attribute in the form with a return state. Thus the form will wait until the JavaScript returns true before proceeding with submit.
The HTML
<form action="something.php" onsubmit="return someJsFunction()">
<!-- form elements -->
<input type="submit" value="submit">
</form>
The JavaScript
function someJsFunction(){
//your validations or code
if(condition == false){
return false; // This will prevent the Form from submitting and lets
// you show error message or do some actions
}else{
return true; // this will submit the form and handle the control to php.
}
}
You can do this with the jQuery submit callback for this
$("form").submit(function(){
alert("Submitted");
});
see. https://www.w3schools.com/jquery/event_submit.asp
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