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
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 have a JavaScript that changes the attribute of the input button to "disabled", so the user don't submit the page twice.
// Disables multiple submit
function disableSubmit (btn, submitForm) {
// Sets button as disabled, changes class and cursor
$(btn).attr("disabled", true);
$(btn).toggleClass("disabled alt2");
$(btn).css('cursor', 'initial');
$(btn).attr("value", "Sender...");
// Submits form
$(submitForm).submit();
}
// Disables submit for order form
$("#send-order").click(function () {
return disableSubmit(this, "#order");
});
The problem is that I need to track the name of the button submitting the page so I can handle it in my Django view.py file.
HTML
<input value="Send bestilling" id="foo" name="send-order" type="submit" class="button alt2">
View.py
request.POST.get("send-order", False)
But if I use my script to submit the page, I can't get the name of the input submitting the page. Is there any way to set a name for the button submitting the page in my script?
I tried this but didn't work:
$(submitForm).submit().attr("name", "send-order");
Solution
I had to change the code inside views.py in order to make this work.
you can use preventdefault or return false
$("#send-order").click(function (event) {
event.preventDefault();
return disableSubmit(this, "#order");
});
Or
<input id="send-order" value="Send" type="submit" onclick="disableSubmit(this, '#order');return false" />
One way you can do this is by creating a hidden input on your form, with a name of its own. Something like below.
<input type="hidden" name="buttonName" id="buttonName" />
Then, in your disableSubmit function, make it set the value of that input before submitting.
$(submitForm)
.find("input[name=buttonName]")
.attr("value",
$(btn).attr("name")
);
From there, you can just retrieve the "buttonName" value in your View.py.
The codes posted might be not consistent because I am continuing someone's work and trying not to make too much changes if possible.
Anyways, there's this form which has inputs for others to input values.
upon submitting, if the input field is empty an alert will pop up and should stop the form from submitting.
I have tried using both return false; and event.preventDefault(); inside the if input field is empty but the form still submits.
trying to cut this short because the script is hell lots
just a simple form
<form action="cart.php" method="post" name="ordering" id="ordering" onsubmit="addDesc();">
<button type="submit" class="add-to-cart" alt='Add this product to your shopping cart now.'>Add to Cart <span class="fa fa-cart-plus"></span></button>
</form>
the function
function addDesc(desc){
// some variables to be passed when form submits
// an $.each function to loop through something
//inside the loop it'll push input values into an array called checkEmpty
if(jQuery.inArray("", checkEmpty) !== -1){
alert('Please Do not leave any input fields empty.');
return false;
}else{
//some outputs
}
}
return false is the first I tried but form still submitted.
I even tried something like
$('.add-to-cart').on('click', addDesc(event));
and inside addDesc() instead of return false I used event.preventDefault()
Thanks in advance.
Very simple. Just add a return before calling the function onsubmit:
<form action="cart.php" method="post" name="ordering" id="ordering" onsubmit="return addDesc();">
Should do the trick (returning true or false will send the form or prevent the submission).
Take a look at Working example.
HTML :
<form action="cart.php" method="post" name="ordering" id="ordering">
<button type="submit" class="add-to-cart" alt='Add this product to your shopping cart now.'>Add to Cart <span class="fa fa-cart-plus"></span></button>
</form>
JS :
$( "#ordering" ).submit(function( event ) {
if(jQuery.inArray('', checkEmpty) !== -1){
alert('Please Do not leave any input fields empty.');
event.preventDefault();
}else{
alert('submiting');
}
});
You're using JQuery so you don't have to use inline onsubmit.
Hope this helps.
You are executing addDesc at the time of binding it, so the return value of that function is used.
Try this
$('.add-to-cart').on('click', addDesc);
or
onsubmit="addDesc"
change the button type as 'button" instead of 'submit'.And then you can call the function in the event of the button click.
I am trying to submit my form named 'vform' by using javascript and ajax.Here
Button named 'show' is being used to show the 'div' containing form named vform and that form calls codevalidate function and there it submits the form using some ajax code..Where i am getting error is vform.submit().Here's the html and js code(I know error is in if condition but do not know where)
html:
<button id="show" onClick="javascript:codefield(); return false";>Apply for Discount</button>
<div id="apply" style="display:none">Voucher code<br>
<form id="vform" name="vform" action="" method="post" onsubmit="javascript:codevalidate(); return false;" >
<input type="text" name="code" id="code"><br>
<span id="error" style="color:red"></span><br>
<input type="submit" name="btn" value="apply" id="btn" ></form>
</div>
javascript:
function codevalidate()
{
if(document.getElementById('code').value!=="")
{
$.post("couponajax.php",{code:$("#code").val()},
function(data)
{
if(data=='1')
{
//alert("success");
vform.submit();
return true;
}
else
{
document.getElementById('error').innerHTML="You have entered a wrong code!";
return false;
}
});
}
else
{
document.getElementById('error').innerHTML="Code can't be empty!";
return false;
}
return false;
}
codefield function is just displaying the div on onclick event and ajax call is just checking whether the code exists in database or not..if exists returns 1 else 0.
The problem is alert message is being displayed but form is not being submitted. How can I fix this problem?
I think you are missing jquery selector.
Try to replace
vform.submit();
with
$("#vform").submit();
or you can call submit button click event like
$("#btn").click();
You are not selecting the form.
Try changing;
vform.submit();
To:
$("#vform").submit();
Please try this one, works for me.
document.getElementById("vform").submit();
Try this
document.forms["vform"].submit();
Hope this helps.
You don't have to submit form with code.
Just call validation function and control submit flow with preventDefault function.
var codevalidate = function(e) {
if (!validationCode) { // if validation code didn't pass
e.preventDefault(); // prevent form from submitting
}
}
// register callback that will be called when user submits form
document.getElementById("vform").addEventListener('onsubmit', codevalidate);
That way form will be submitted by user only if validation pass.
Also check if your data is actually returning '1' by calling console.log(data);
Form will be submitted to the current address if action is empty, is that ok?
The thing is that:
action attribute of your form element is empty. So it is being submitted but to the same page from which it is calling the .submit() method.
so you should specify action attribute first of all like:
<form id="vform" name="vform" action="vfrom_submit.php" method="post"
onsubmit="javascript:codevalidate(); return false;" >
.....
</form>
Also try changing
vform.submit();
to:
$("#vform").submit();
//OR
// document.getElementById("vform").submit();
// Although vform.submit() can also work.
Hope it helps, cheers :)!
You should use:
document.getElementById("vform").submit();
Update:
Try removing "return false;" from onsubmit attribute and remove "vform.submit();" from the if condition as well.
I have the form like below
<form id="myform" class="form-horizontal" class="collapse in">
<fieldset>
<!-- form fields are here -->
<div class="form-actions">
<button class="btn btn-inverse" id="search" name="search" data-loading-text="Searching...">Search</button>
</div>
</fieldset>
</form>
And I use the following code to act once button is pressed:
$("#search").click(function() {
try {
// some javascript with syntax error is here
} finally {
return false; // don't submit form automatically
}
});
But if my javascript contains syntax errors, then the form is submitted regardless of try .. finally. How can I fix that? The form should be never submitted automatically.
Set the button type to "button".
button: The button has no default behavior. It can have client-side
scripts associated with the element's events, which are triggered when
the events occur.
<button type="button"...>Search</button>
The form won't submit at all if that is the case until you tell it to explicitly submit via Javascript.
See HTML5 specs for this simple solution. http://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#attr-button-type
Set the action of the form to something that isn't correct, like action="error.html". Then as the final step in the form submit process, dynamically set the action to the correct link.
You can also make the button not submit at all, and submit the form manually:
$('#myForm').submit();
Use event.preventDefault at the beginning of the event and trigger the submit yourself.
$("#search").click(function(event) {
event.preventDefault();
// some javascript with syntax error is here
var foo = "bar";
alert(foobar); // ERROR
// if syntax error occurs in this scope, the form won't submit
$(this).closest("form")[0].submit();
});
DEMO
$("#search").click(function(e) {
e.preventDefault();
try {
// some javascript with syntax error is here
} finally {
return false; // don't submit form automatically
}});
on the click function, prevent the default action. Then if the code does pass, then manually call the submit
$('#myForm').submit();