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.
Related
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
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.
<input type="submit" class="sub" onClick="exefunction2()" id="button">
When I click on the submit button onClick is not working. How can I fix this? I need to work this on submitting the form because onClick event contains values.
The best way is to call you method on the form tag like this:
<form onsubmit="return exefunction2();">
...
</form>
Returning false will not submit the form, true will submit!
to post more data (builded with exefunction2) you can use this
<script type="text/javascript">
function exefunction2(form) {
//add dynamic values
var dynValues = {
"val1": 1,
"val2": "bla"
};
for(var name in dynValues) {
//check if field exists
var input = null;
if(document.getElementsByName(name).length === 0) {
input = document.createElement('input');
input.setAttribute('name', name);
input.setAttribute('type', 'hidden');
form.appendChild(input);
}
else {
input = document.getElementsByName(name)[0];
}
input.setAttribute('value', dynValues[name]);
}
return true;
}
</script>
<form onsubmit="return exefunction2(this);">
<input type="submit" />
</form>
W3 schools has a good explanation here: http://www.w3schools.com/js/js_validation.asp
Basically, submit waits for a return value from onClick before doing anything. You can wire up a confirm() request too, if you like. If the form validates, just write something like return confirm("continue"). It's an old question, but I hope it helps anyone who stumbles across it. Another big reason for failure is a bug in your script. Unfortunately, unless you are running a debugger in your browser, it is very difficult to know what if anything is crashing your script. Turning on your browser debugger can be helpful to trace any issues. In Chrome you can use CTRL-SHIFT-I for Windows or CMD-OPTION-I for Mac. If you pause on caught errors, you can find any syntax or fatal errors that are prematurely stopping your script.
You can submit the form with Javascript.
<form id="form_id" ...>
<input type="button" class="sub" onclick="exefunction2();" id="button">
The Javascript:
function exefunction2() {
...
document.forms["form_id"].submit();
}
Well, I don't know if that's the "official" expected behavior, but that's how it works: a submit-type button will no longer submit if you add to it an onclick Javascript function. Just have the function also submit the form or have the function return false
Try <form onSubmit="exefunction2()">.
Agreeing to #silly , I used the same idea . I am sharing the implementation. My objective was , to disable a button "Execute" which is used to submit a form , until a response is received , upon which , the "execute" button should be enabled again. I am using Flask .
My Form:
<form onsubmit="return disableExecuteButton();" method="POST" action="/dothis">
.....
</form>
My JS:
function disableExecuteButton(){
var executeButton = document.getElementById("executeButton");
executeButton.setAttribute("disabled","disabled");
return true;
}
function reactivateExecuteButton(){
var executeButton = document.getElementById("executeButton");
executeButton.setAttribute("disabled","enabled");
}
From Flask, I return:
return render_template('result.html', message=message, error=error, html_content=result, history=session['actions_taken'], done=True)
The "done=True" , is what I use to indicate, that the response is received and we need to enable the button again.
To re enable the button:
{% if done %}
<script type="text/javascript">
reactivateExecuteButton()
</script>
{% endif %}
Change the event to onsubmit, and return false to avoid the form to be submitted.
<input type="submit" class="sub" onsubmit="exefunction2();return false;" id="button">
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();
I need to get an .click() event and prevent form from behaving as it was initially designed and make my own changes and submit. How is it possible?
EDIT: Form input actually has an onclick defined behavior. I need to redefine it somehow.
EDIT: Some code
<form action='link' method='get'>
<input type="image" name="name" id="id" class="class" onclick="this.form.action='some_link'" title="Title" value="" src="image.gif">
</form>
If you don't want it to submit the form, return false at the end of your click function. If you want to submit the form, use the form element and call the submit function on it:
$('#myFormID').submit();
$('#form').submit(function(e) {
// Some code
});
I think it's enough.
You could use something like this (haven't tested it but it should work)
form = $("#yourform");
button = $("#yoursubmit");
button.click(function(){
dosomething();
form.submit();
return false;});