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();
}
});
Related
$.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.
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>
I have been doing some research for this topic and the answers doesn't seem to help me.
I am trying to invoke a method with jquery's ajax callback and it doesn't seem to be working.
Its giving me the following error message
TypeError: this_obj.password_change_request is not a function
Below is the code I am using:
function resetPass() {
// The following code validates the email text field and submit request for password change.
function password_change_request(queryStr) {
$.ajax({
type: "POST", url: "script/password_change_request.php",
data: queryStr
});
}
this.resetPassRequest = function () {
$("#reset_password").click(function () {
var this_obj = this;
var email_address = $("#email_reset").val();
if (email_address == "") {
return false;
} else {
var queryStr = "email=" + email_address + "&store=" + "<?=$store_dir_name?>";
this_obj.password_change_request(queryStr);
return false;
}
});
}
}
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');
}
});
...
I have been working on a JavaScript validator, but for some reason, evalid always returns as false even if it has passed validation... this is a bug as if evalid is false, the form doesn't submit.
function signup_validate()
{
document.getElementById("email_error").innerHTML = "";
document.getElementById("password_error").innerHTML = "";
evalid = false;
pvalid = false;
email = null;
pass = null;
confpass = null;
email=document.forms["signup_form"]["email"].value.replace(/^\s+|\s+$/g, '');
atpos=email.indexOf("#");
dotpos=email.lastIndexOf(".");
pass=document.forms["signup_form"]["pass"].value;
confpass=document.forms["signup_form"]["confpass"].value;
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
document.getElementById("email_error").innerHTML = "<span class='required'>Email must be valid.</span>";
}
else
{
$.post('/resources/forms/signup.php',{email: email}, function(data){
if(data.exists){
document.getElementById("email_error").innerHTML = "<span class='required'>This email is already in use.</span>";
}
else
{
evalid = true;
}
}, 'JSON');
}
if (pass!=""&&pass!=null&&confpass!=""&&confpass!=null&&confpass==pass)
{
pvalid = true;
}
else
{
document.getElementById("password_error").innerHTML = "<span class='required'>Both passwords must match and cannot be left blank.</span>";
}
alert(evalid);
if (evalid == true && pvalid == true)
{
document.getElementById("signup_form").submit();
}
else
{
return false;
}
}
What could I have missed?
The only moment when you set "evalid" true is inside a function that runs asynchronously. In other words, by the time you set "evalid" true the main function has already reached the end.
You Could try to use $.ajax instead of $.post and use the parameter async:false
Try something like this:
$.ajax({
type: 'POST',
url: '/resources/forms/signup.php',
data: {email: email},
success: function(response){
//your function here
},
dataType:'JSON',
async:false
});