jQuery prevent submit of form inside of if statement - javascript

Sorry if there are some mistakes, but I am a total noob and I am also posting for the first time on StackOverflow.
I am trying to configure a submit form, that controls if the inserted PIN is right, and if so goes on with the submission. I did some online research and found out that with jQuery we can use to function event.preventDefault(), I tried to insert it inside my AJAX request but it looks like it doesn't stop the form from being saved.
The code looks like these:
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp" : otp,
"PIN" : PIN,
"action" : "verify_otp"
};
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
error : function(event) { event.preventDefault(); };
}
//if I insert "return false;" here the submit is always blocked
}
I checked on atom if the parenthesis are right and it looks like it is.
Any ideas how I should use the preventDefault()?
I also checked if the output of m_ajaxpinr.php is correct, and it is. I also tried like these but it still didn't work...
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
$("form").submit(function(event) {
if (response.type == 'success')
{
alert(response.type);
}
else if (response.type == 'error')
{
alert(response.type);
event.preventDefault();
}
});

as said in comment above ajax call is asynchronous, you need to complete cancel default action for the form or put event.preventDefault(); on the top function, then submit it in success function if it valid otp.
.val() will not return null, it return empty if no input.
$('#myForm').on('submit', verifyOTP);
function verifyOTP(e) {
e.preventDefault(); // note this
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp": otp,
"PIN": PIN,
"action": "verify_otp"
};
if (otp) { // mean not null, undefined, empty, false, 0
$.ajax({
//url: 'm_ajaxpinr.php',
url: 'https://httpbin.org/anything/test',
type: 'GET',
dataType: "json",
data: input,
success: function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
if(response.args.otp == 1234){
console.log('valid otp, continue submission')
$('#myForm').off('submit'); // remove submit event
$('#myForm').submit(); // then submit the form
}
else{
console.log('invalid pin,\nvalid pin: 1234');
}
},
error: function() {
console.log("server error, submission cancelled");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
console.log("otp maybe empty, submission cancelled");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input id="contomovimentato">
<button>submit</button>
</form>

Related

Get the ajax return value on successful output from php as true or false [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm wanting to use AJAX to determine whether or not a form's values are acceptable to me (this is not form validation). The AJAX result will determine if the form is submitted or not.
Below, you'll see that I perform an AJAX call when the form is submitted and depending what is returned (either blank which is acceptable, or an error message which is not acceptable), I'd like to return true; or return false; the $("form").submit.
I suspect my trouble to be in the AJAX's success:. Please help me get the result out of the AJAX call so that I can do something like if (result == "") { return true; } else { return false; }.
WORKING:
$("form").submit(function(e) {
e.preventDefault();
var form = this;
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "")
form.submit();
else
alert(result);
}).fail(function() {
alert('ERROR');
});
});
ORIGINAL:
$("form").submit(function() {
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
success: function(result) {
alert(result);
},
error: function(result) {
alert(result); //This works as expected (blank if acceptable and error msg if not acceptable)
}
});
/*
if (result == "")
return true;
else
return false;
*/
return false; //this is here for debugging, just to stop the form submission
});
As the ajax call is asynchronous, you have to prevent the form from submitting, and then when a result is returned, you check if it matches the condition and submit the form with the native submit handler, avoiding the preventDefault() in the jQuery event handler :
$("form").submit(function(e) {
e.preventDefault();
var self = this,
tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "") self.submit();
}).fail(function() {
alert('error');
});
});
use e.preventDefault(); to prevent the form from submitting, and then use this.submit() (isn't calling the jQuery .submit() trigger function, but rather the native <form> .submit() function) to submit the form.
$("form").submit(function(e) {
e.preventDefault();
var tray = $('select[name=tray_id]').val();
var form = this;
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
complete : function(result){callback(result, form)}
});
});
var callback = function(result, form){
if(!result)
form.submit();
};

Ajax submit an ajax loaded form

I load replies to comments asynchronously in php like in youtube comments.
The ajax handler for forms (ie reply forms) loaded like this is not working. e.preventDefault() is not working. The forms are submitted to the action page itself and page is redirected to action url. If i edit a reply. It works but page is redirected to the action url. This happens only for the ajax loaded replies. The same handler is used for regular comments and it works fine.
A comment :
A comment with loaded replies :
When a reply is edited it just goes to /path/to/submit.php and shows the value of json output like this
result on submitting a reply form
Ajax to show or hide replies:
//load or hide replies
function loadmore(id) {
var val = $('#' + id).data("value");
var count = $('#' + id).data("count");
$.ajax({
type: 'post',
url: '/path/to/submit.php',
data: {
replyof: val
},
success: function(response) {
var content = document.getElementById("show" + val);
content.innerHTML = response;
var clicknum = $('#' + id).data("clicknum");
$('#' + id).data("clicknum", 2);
if (!$("#show" + val).is(":hidden") && clicknum != 1) {
document.getElementById(id).innerHTML =
' View all ' + count + ' replies <i class="fas fa-angle-down"></i>';
$("#show" + val).hide();
} else {
document.getElementById(id).innerHTML =
'Hide all replies <i class="fas fa-angle-up"></i>';
$('#show' + val).show();
}
}
});
}
I use the same class for comments as well as replies and ajax submit the form to the same page /path/to/submit.php using
eg
<form class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
The form handler
$(".replyform").submit(function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
The .replyform render by ajax so use on instead of traditional way
$(document).on("submit", ".replyform",function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
I think your calling your form wrong. You need an id attribute. I don't think you can call it by it's class name like that.
<form id="myForm" class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
$("#myForm").submit(function(e) {
...rest of script.

Only send post/get if form values has changed

I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...

Stay on the page with jQuery Validate plugin

When I click on the submit button of my form I'm redirected because of the PHP on the page "Form sent". How to stay in the same page with jQuery validate form plugin please ?
PHP FILE
<?php
// [I HAVE CUT THE CODE]
if(mail($to, $subject, $message, $headers)){
echo "Form sent";
} else {
echo "Form not sent";
}
?>
JQUERY FILE
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
form.submit();
}
});
HTML FILE
<form id="form-contact" action="php/traitement.php" method="post"></form>
UPDATE 1
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){ console.log("success!", result);},
dataType: dataType
});
return false;
}
I'm always redirected on "Form sent" page. I know nothing about Ajax :-/
UPDATE 2
http://jsfiddle.net/Xroad/2pLS2/25/
jQuery .ajax() can be used to submit data to the server without a page refresh, but it's not exclusive to the jQuery Validate plugin.
However, here are your two options using the jQuery Validate plugin.
Standard form submit using the default action of the form element (as you've done)...
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
form.submit(); // standard submit of the default form action
}
});
To stay on same page, use .ajax() in the submitHandler callback...
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
$.ajax({ // submit form using ajax
// your ajax options here
});
return false; // block default form action
}
});
See the jQuery .ajax() documentation for the options.
This is your own jsFiddle, which shows everything is working. I cannot test the ajax but the form is not refreshing the page as you claim.
If I understand correctly what you want, one way would be to try to submit from jQuery. In the submitHandler have something like:
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){ console.log("success!", result);},
dataType: dataType
});
The tricky part would be to get all the information into the data object before calling this.
The success function would have the data from the server after posting.
More info: https://api.jquery.com/jQuery.post/
If you make it work without validate plugin and more organised validation process then I would like you to have a look my code:
jQuery(document).ready(function($) {
$('#MyForm').on('submit', function(){
var form = this;
if(validateForm(form)) {
var values = $(form).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
event.preventDefault(); //changed to allow the tag manager to notice that the form was submitted
}
else{
event.preventDefault();
return false;
}
});
// validate Form
function validateForm(form) {
valid = true;
$(form).find('input[type=text], input[type=email]').each(function(i, val){
if(validateField(val, true) == false) { valid = false; }
});
return valid;
}
// validate all form fields
function validateField(field, submit) {
var val = $(field).val();
if($(field).attr('aria-required') == 'true' && submit){
if(val == '') {
$(field).parent().removeClass('valid');
$(field).parent().addClass('error');
return false;
}else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
// you can more specific
if($(field).attr('type') == 'text') {
$(field).parent().addClass('error');
return false; }
else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
// you can more specific
if($(field).attr('type') == 'email') {
$(field).parent().addClass('error');
return false; }
else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
}
}
// Run validation before Submit the form
$('input[type=text], input[type=email]').on('change', function(){
if($(this).val() != ''){
$(this).parent().removeClass('error valid');
validateField(this, false);
}
});
});

jQuery - Resume form submit after ajax call

Is it possible to stop a form from submitting and then resubmitting the same form from within the success of an ajax call?
At the moment it gets to the success bit but it doesn't resubmit the form which should submit and redirect the user to the http://example.com website.
Thank you very much for any help in advance
If it's not possible to do it this way, is there another way of getting it to work?
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
$('form').attr('action', 'http://example.com');
$('form').unbind('submit').submit(); // mistake: changed $(this) to $('form') - Problem still persists though it does not resubmit and redirect to http://example.com
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
});
});
Edit:
Stackoverflow posts checked out for the code below:
Resume form submission after $.ajax call
How to reenable event.preventDefault?
I just thought I'd mention I have also tried this code without avail.
var ajaxSent = false;
$(document).ready(function() {
$('form').submit(function(e) {
if ( !ajaxSent)
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
alert('submit form');
ajaxSent = true;
$('form').attr('action', 'http://example.com');
$('form').submit();
return true;
}
else
{
alert('Your username/password are incorrect');
return false;
}
},
error: function() {
alert('There has been an error, please alert us immediately');
return false;
}
});
});
});
I have also tried this code without any luck as well.
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
$('form').attr('action', 'http://example.com');
$('form').unbind('submit').submit();
return true;
}
else
{
alert('Your username/password are incorrect');
return false;
}
},
error: function() {
alert('There has been an error, please alert us immediately');
return false;
}
});
});
});
Solution was quite simple and involved adding and setting async to false in .ajax(). In addition, I have re-worked the code to work of the submit button instead which submits the form when the AJAX passes successfully.
Here is my working code:
$(document).ready(function() {
var testing = false;
$('#btn-login').on('click', function() {
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
async: false,
success: function(data) {
if (data == 'true')
{
testing = true;
$('form').attr('action', 'https://example.com');
$('form').submit();
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
return testing;
});
});
It's no good practice to reselect all form tags throughout your code, what if you have multiple forms on the page?
Also you'd better use .on() and .off() with jQuery.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
// cache the current form so you make sure to only have data from this one
var form = this,
$form = $(form);
$.ajax({
url: form.action,
type: form.method,
data: $form.serialize(),
success: function(data) {
if (data == 'true')
{
$form.attr('action', 'http://example.com').off('submit').submit();
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
});
});
In one line you use $('form') to select the form to change its action, but then you use $(this) to try to select that same form. I would guess that this inside the callback function isn't what you expect it to be, and is something other than your form (possibly the window object).
Just chain the calls:
$('form').attr('action', 'http://example.com').unbind('submit').submit();

Categories