Can't use preventDefault() with if, else - javascript

$.get in the code below returns a boolean value in JSON format named data. But whether the value of data is false or true preventDefault() prevents the submission of the form anyway.
$(document).ready(function() {
$("#username").blur(function() {
let username = document.getElementById("username").value;
$.get("/check", {
username_value: username
}, function(data) {
alert(data);
$("#submit").click(function(e) {
if (data) {
e.preventDefault();
} else if (!data) {
e.submit();
}
});
});
});
});
And this is the /check part
#app.route("/check", methods=["GET"])
def check():
"""Return true if username available, else false, in JSON format"""
get_username = request.args.get("username_value")
users = db.execute("SELECT username FROM users")
lenght = len(get_username)
i = 0
for user in users:
if get_username == users[i]["username"] or not lenght > 1:
return jsonify(True)
i += 1
return jsonify(False)
I am very new at coding business btw. Thanks for help.

Try change to capture the event from form ID instead of button this way:
$("#form").submit(function (e) {
if (!data) {
e.preventDefault();
} else {
e.submit();
}
});
e.submit() must be used in event from a submited form.
Make sure data is boolean type. and don't forget change the selector to your form ID.

I solve the problem by replacing the $.get with $.ajax. I guess the problem was about the fact that $.get only works async. So I used $.ajax's async paramater at false. Then it worked just as I want.
Last version of the code:
$(document).ready(function() {
$('#form').submit(function(e){
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let confirmation = document.getElementById("confirmation").value;
var boolean_data;
$.ajax({url: "/check?username=" + username, type: 'get', async: false, success: function(data){boolean_data=data;}});
if(!boolean_data) {
alert("\"" + username + "\"" + " username is already taken.");
e.preventDefault();
}
else if(!password || !confirmation) {
alert("Pls povide a password and confrim it");
e.preventDefault();
}
else if(password != confirmation) {
alert("Passwords don't match");
e.preventDefault();
}
});
});
Thanks to everyone who commented and answered my question.

Related

jQuery prevent submit of form inside of if statement

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>

Form is submitted even after using e.preventDefault()

I have a form which checks for the ifsc code of before form submission, The api returns "failure" if wrong ifsc is given. If the response is a failure, the form shouldn't be submitted. I used e.preventDefault(e) but it didn't help.
$('#corporate-signup').on('submit',function(e){
var ifsc_code = $('#ifsc-code').val();
var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
$.get(api_url, function(data, status){
if (data.status === "failure") {
$('.bank-details').addClass('no-ifsc').text(data.message);
e.preventDefault(e);
}
else{
$('#corporate-signup').submit()
}
});
});
I don't know what is the mistake here. I have also tried to return false instead of preventDefault() but even it didn't work.
I think that because you use an async function and don't return false, it goes ahead and submits before waiting for an answer - it doesn't know to wait for the callback.
Since you manually submit inside the async callback, try to add e.preventDefault(e); after the $.get:
var shouldSubmit = false;
$('#corporate-signup').on('submit',function(e){
if (!shouldSubmit) {
// First time entering, this won't submit due to line below
e.preventDefault(e);
var ifsc_code = $('#ifsc-code').val();
var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
$.get(api_url, function(data, status){
if (data.status === "failure") {
$('.bank-details').addClass('no-ifsc').text(data.message);
}
else{
shouldSubmit = true;
$('#corporate-signup').submit()
}
});
}
});
Edit: added shouldSubmit boolean, since otherwise it would keep hitting e.preventDefault(e) and never submitting. Upon a successful result from the async request, you can set it to true and resubmit.
Try this
$('#corporate-signup').on('submit',function(e){
e.preventDefault();
var ifsc_code = $('#ifsc-code').val();
var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
$.get(api_url, function(data, status){
if (data.status === "failure") {
$('.bank-details').addClass('no-ifsc').text(data.message);
}
else{
$('#corporate-signup')[0].submit() // bypass jQuery bound event
}
});
});

Jquery form validation with ajax

i need to check if username exist. If it exist, I increment a variable "form_error".
If "form_errors" is > 0, then i stop code with return false.
But, when i make an Ajax call, i cannot increment this variable. Probably is it a scope / visibility problem?
So, in the case that i have an error on username, my form_errors will be forever 0 and form is submit...
How i can increment that form_errors?
Thank you to all, I leave a piece of code
$('#add-sponsor').submit(function() {
var form_errors = 0;
var username = ('#username').val();
$.ajax({
url : location.protocol + '//' + location.host + '/commands.php?action=check-username',
data : {
username : username
},
type : 'post'
}).done(function (result) {
if (result=='false') {
$('#username').parent().addClass('has-error');
$('#username').parent().removeClass('has-success');
$('#username').parent().next('.help-block').text('Questo username già esiste');
form_errors++;
} else {
$('#username').parent().addClass('has-success');
$('#username').parent().removeClass('has-error');
$('#username').parent().next('.help-block').text('');
}
}); // ajax
if (form_errors > 0) {
return false;
}
console.log(form_errors); // <- this is forever 0
}
$.ajax function is asynchronous so will continue execution of
if (form_errors > 0) {
return false;
}
before the done function is executed.
if (form_errors > 0) {
return false;
}
console.log(form_errors); // <- this is forever 0
You check here if you have errors, and if so, you return...so, the console.log will never be hit, unless you have no errors. Maybe just use...
if (form_errors > 0) {
console.log(form_errors);
}
Your best bet might be to use some sort of variable outside your submit function
eg
var isValid = false;
$('#add-sponsor').submit(function() {
if(!isValid)
{
var form_errors = 0;
var username = ('#username').val();
$.ajax({
url : location.protocol + '//' + location.host + '/commands.php?action=check-username',
data : { username : username },
type : 'post'
}).done(function (result) {
if (result=='false') {
$('#username').parent().addClass('has-error');
$('#username').parent().removeClass('has-success');
$('#username').parent().next('.help-block').text('Questo username già esiste');
isValid = false;
$('#add-sponsor').submit();
} else {
$('#username').parent().addClass('has-success');
$('#username').parent().removeClass('has-error');
$('#username').parent().next('.help-block').text('');
isValid = true;
$('#add-sponsor').submit();
}
}); // ajax
return false;
}
return true;
}
Considered using the jQuery validation plugin? You could set up your form using a remote validation rule to check whether the username ist valid. jQuery validation let's you implement your callbacks within the submitHandler or the invalidHandler.
Try this code if you want to test it. Just make sure to include the jquery.validate.js as well as additional-methods.js into your page.
var validator = jQuery("the-sponsor-form").validate({
messages: {
username: {
remote: 'Questo username già esiste'
}
},
rules: {
username: {
required: true,
remote: {
url: location.protocol + '//' + location.host + '/commands.php?action=check-username',
type: 'post',
data: {
username: $('#username').val();
}
}
}
},
submitHandler: function(form) {
alert("now submit the form");
jQuery(form).submit();
}
});

How to reset event.preventDefault() of a form submit event?

I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}

jQuery form submit

My goal is:
When for is submitted:
a validation on form is made : OK
an ajax is called to see that username and password do match : OK
if they don't match, display an error: OK
if they match, then REALLY SUBMIT the form: NOT OK.
Infact the trouble is, I cannot submit the form since there is a jquery submit event on it!
function form1Submit() {
var username=$('#username').val();
var password=$('#password').val();
if (username.length<2) {
return false;
}
if (password.length<2) {
return false;
}
$.post("check.php", { username: username, password:password }, function(data) {
if (data=="ko") {
alert('bad password');
return false;
} else {
//to be done here !
}
});
return false;
}
function init() {
$('#form1').submit(function(){
return form1Submit();
})
}
$(document).ready(function(){
init();
})
You can call the native submit event, so do this:
$('#form1').submit(form1Submit);
Then in your post callback do this:
$.post("check.php", { username: username, password:password }, function(data) {
if (data=="ko") {
alert('bad password');
} else {
this.submit();
}
});
The this.submit() isn't calling he jQuery .submit() trigger function, but rather the native <form> .submit() function.
The return false is blocking the default form submit action. You have either to return true from the form1Submit() function to let the default form submit action do its job, or to add another $.post() inside the else which submits the data to the form asynchronously, if your intent was to do it using ajaxical powers.
The problem is that form1Submit always returns false.
function form1Submit(ev, ok) {
ev.stopPropagation();
ok = (typeof ok != 'undefined') ? ok : false;
if (ok)
return true;
var username=$('#username').val(),
password=$('#password').val(),
selfForm = this;
if (username.length < 2)
return false;
if (password.length < 2)
return false;
$.post("check.php", { username: username, password:password }, function(data) {
if (data=="ko") {
alert('bad password');
} else {
$(selfForm).trigger('submit', [true]); // again submit but with ok parameter
}
});
return false;
}
function init() {
$('#form1').bind('submit', form1Submit);
}
$(document).ready(function(){
init();
})

Categories