This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I'm creating a form and I want to validate it in real time. Everythings works in the ajax call, but I have a problem with the returns.
This is the code:
function checkEmail() {
var reg_exp = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
var mail = $("#email").val();
if (!reg_exp.test(mail) || (mail === "") || (mail === "undefined")) {
$("#mail_mess").html("Enter a valid email address");
return false;
}
else {
var r = '';
$.ajax({
type: "POST",
url: "index.php?p=jsform&ajaxcall=checkEmail",
data: {'mail':mail},
dataType: 'json',
success: function(res) {
r = res;
if(res) {
$("#mail_mess").html("OK");
//return true;
}
else {
$("#mail_mess").html("Email already Exists!");
//return false;
}
}
});
//alert(r);
return r;
}
}
$("#email").on("input", function() {
checkEmail();
});
$("#submitButton").click(function() {
if(... && checkEmail()) {
sendForm();
}
else {
$("#form_message").html("<span class='error'>All fields are required</span>");
}
});
As you can see, I call the function checkEmail() on input change (for the realtime validation) and on submit (all fields check before sending data).
The function checkEmail() should return false on invalid email or on already existing email and should return true on valid and non existing email.
Now.. the function works on realtime validation, I get the "non valid", "already exists" or "valid" exactly when I want. The problem is with the returns, because when I return r, it is an empty string (seems like r = res doesn't work).
And if I try to uncomment the returns inside the if(res)/else they don't work as well.
I'm sorry about my bad english! Thanks for any help :-)
checkMail should accept an optional callback, and call it with the result if defined
function checkEmail(callback) {
var reg_exp = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
var mail = $("#email").val();
if (!reg_exp.test(mail) || (mail === "") || (mail === "undefined")) {
$("#mail_mess").html("Enter a valid email address");
if(callback) {
callback(false);
}
}
else {
$.ajax({
type: "POST",
url: "index.php?p=jsform&ajaxcall=checkEmail",
data: {'mail':mail},
dataType: 'json',
success: function(res) {
if(res) {
$("#mail_mess").html("OK");
//return true;
}
else {
$("#mail_mess").html("Email already Exists!");
//return false;
}
if(callback) {
callback(res);
}
}
});
}
}
no need for callback function here
$("#email").on("input", function() {
checkEmail();
});
the fail function defined to avoid repetition because there's now two "false" paths
$("#submitButton").click(function() {
function fail() {
$("#form_message").html("<span class='error'>All fields are required</span>");
}
if(...) {
checkEmail(function(r) {
if (r) {
sendForm();
}
else {
fail()
});
else {
fail();
}
});
Related
I have a script which runs 2 AJAX calls, the first checks that a record exists within a database. If it does this should not move on and the script should stop. The second submits a job.
My problem is that the job is being submitted before the first AJAX call has returned. My code looks something like this:
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
success: function( data ){
if (data.Response == "Success") {
var noresults = data.Results;
if (noresults > 0){
alert('this record id already exists!');
return false;
}
} else {
alert('an error occured');
return false;
}
}
});
} else {
alert('enter a record id');
return false;
}
// second ajax call goes here, which gets called regardless of the output of the ajax call above
Instead of putting the call to the second ajax method at the bottom of your code (where the comments currently are), put it in the "success" function of your first call. This method will only execute once the first call has finished. This is the only way to ensure that the second call does not happen too early. Ajax calls run asynchronously, so the normal flow of the browser is not interrupted. This is deliberate so that long-running calls don't lock up the browser for the user.
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
success: function(data) {
//check here if you want to call submitJob or not
//and call submitJob()
}
});
} else {
alert('enter a record id');
return false;
}
//call this ajax once you varified your condition from success callback of first one
function submitJob() {
//second ajax call goes here
}
You have to use jquery promise function for that which will wait for the first ajax request to complete then make another ajax request.
JQUERY PROMISE
OR
Put the second ajax request in the success function of first one, and make it happen when you want it to fire
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
success: function(data) {
//check here if you want to call submitJob or not
if (noresults > 0){ return false }
else { Job(); };
}
});
} else {
alert('enter a record id');
return false;
}
function Job() {
//another ajax call.
}
Hope it helps :)
try this: make async propety false
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
async : false, //added this
success: function( data ){
if (data.Response == "Success") {
var noresults = data.Results;
if (noresults > 0){
alert('this record id already exists!');
return false;
}
} else {
alert('an error occured');
return false;
}
}
});
} else {
alert('enter a record id');
return false;
}
OR
perform second ajax call in success function of first ajax call i.e. see comment
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
success: function( data ){
if (data.Response == "Success") {
var noresults = data.Results;
if (noresults > 0){
alert('this record id already exists!');
return false;
}
//perform 2nd ajax call here
} else {
alert('an error occured');
return false;
}
}
});
} else {
alert('enter a record id');
return false;
}
I have code in that javascript and ajax call need to be work simultaneously. But it did not work. And always go to return true.
Functionality of create function is validation of data and ajax call which execute query and depend on result it will further execute. If response text is yes then it call confirmval function. And then further it ask for confirmation and next execution But I face problem is function not return false it always go to true. I cant understand why this happening?
function create()
{
if (document.companyregister.cmpname.value === "")
{
alert("Please Enter Company name");
document.companyregister.cmpname.value = "";
document.companyregister.cmpname.focus();
return false;
}
var companyname = document.companyregister.cmpname.value;
var username = document.companyregister.username.value;
$.ajax({
url: 'checkexisting.php',
type: 'POST',
data: {companyname: companyname,username:username},
success: function(errorResponse) {
var result = errorResponse.trim();
if(result=="yes"){
return confirmval(companyname,username);
}
else{
document.getElementById("formsubmitting").style.display = "block";
document.getElementById("hidesubmit").style.display = "none";
return true;
}
}
});
}
function confirmval(companyname,username){
var c = confirm("This company is already created.\nWould you like to delete existing company?");
if(c){
alert("c");
$.ajax({
url: 'updatecompany.php',
type: 'POST',
data: {companyname: companyname,username:username},
success: function(responsetext) {
var result = responsetext.trim();
if(result=="yes"){
document.getElementById("formsubmitting").style.display = "block";
document.getElementById("hidesubmit").style.display = "none";
return true;
}
}
});
}
else{
alert("notc");
window.location="http://www.google.com";
}
}
You are trying to return two values after your first ajax call:
if(result=="yes"){
return confirmval(companyname,username);
return false;
}
This will just return the result of confirmval function (which appears to always return true), and the 'return false' line will never be run, thus it will always return true.
If you need that result=="yes" to return false, I might recommend something like:
if(result=="yes"){
var confirmvalResult = confirmval(companyname,username);
if(confirmvalResult) {
return false;
} else {
// not sure what you want to do here
}
}
I am trying to evaluate a form text/email field to see if there is something there and if so, run it past a regular expression valuation. It worked fine when I included the regex code in the SendEmail function with the rest of the logic but when I tried to move the regex part out into it's own function(validateEmailAddress), the validation still works but it doesn't seem to want to return false and just stop. Instead it continues on to the ajax part and sends the email regardless of whether it passes the regex test or not. It's the same code so I'm not sure why the "return false" doesn't work once the regex piece is moved out into it's own function.
Any thoughts are appreciated and THANK YOU!
function validateEmailAddress(address) {
filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!filter.test(address)) {
alert(address + ' - Is an invalid email address.');
return false;
}
}
function SendEmail() {
var emailFromVal = document.getElementById("EmailFrom").value;
var emailToVal = document.getElementById("EmailTo").value;
if (emailFromVal != 0) {
validateEmailAddress(emailFromVal);
} else {
alert("Please provide your email address.");
return false;
}
if (emailToVal != 0) {
}
else {
alert("Please provide your friend's email address.");
return false;
}
$.ajax({
method: 'POST',
url: '/_ajax/emailshare/',
dataType: 'json',
data: formCollection,
success: function (data) {
///send that email out
}
});
}
You are not doing anything with the return value from validateEmailAddress(), try this:
if (emailFromVal != 0) {
if(!validateEmailAddress(emailFromVal)){
return false;
}
} else {
alert("Please provide your email address.");
return false;
}
also, you need to return true from validateEmailAddress() when the email is valid:
function validateEmailAddress(address) {
filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!filter.test(address)) {
alert(address + ' - Is an invalid email address.');
return false;
}
return true;
}
return false; in validateEmailAddress will return just from validateEmailAddress, not from the enclosing function (SendEmail).
Your options are:
Check the return value of validateEmailAddress from the enclosing
function:
if(!validateEmailAddress(address)) return false;
OR
Throw from validateEmailAddress and catch the error from the
enclosing function (this'll allow the error to propagate up the
stack to an arbitrary length until you catch it--i.e., you don't
have to catch just from the enclosing function but also from its
caller or it's caller's caller, and so on and so forth).
I want to check internet connection with a test, with jquery
my js:
/* detect connexion */
function detectConnexionTest() {
var urlOnline = "/connect";
jQuery.ajax({
type: 'POST',
url: urlOnline,
success: function(data, textStatus, xhr) {
console.log(xhr.status);
detectConnexion("yes");
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.status);
detectConnexion("no");
}
});
}
function detectConnexion(value) {
if (value == "yes") {
return true;
} else if (value == "no") {
return false;
} else {
return false;
}
}
and after, the calling in a angularjs controller :
detectConnexionTest();
if (detectConnexion() === true) {
$scope.online = "connected";
} else if (detectConnexion() === false) {
$scope.online = "not connected";
}
html :
<p>are you connected ? : {{online}}</p>
i'm confused about call the testing function detectConnexionTest , and my scope show me always "not connected" even if i'm connected and get "200" status... what's wrong ?
You call detectConnexionTest() which begins an AJAX request and returns immediately
You call detectConnexion() with no parameter immediatly afterwards, which is guaranteed to return false even if your AJAX request had completed
When your AJAX call does return, you call detectConnexion() and do pass a value and it will return true or false, but you don't store that return value.
Since you're using jQuery.ajax(), angular does not know when your call returns so even if you did update a value on your scope properly your page would not update until angular went through another digest cycle.
What you should probably do is use $http and set the scope value when the call returns:
function TestCtrl($scope, $http) {
function detectConnexion() {
$http.post("/connect").success(function(data, status, headers, config) {
$scope.online = "connected";
}).error(function(data, status, headers, config) {
$scope.online = "not connected";
}
}
detectConnexion();
}
You're getting it wrong, try to understand how AJAX works, this is one way to do it pretty similar to what you've got there:
Change the detectConnexion function to this:
function detectConnexion(value) {
if (value == "yes") {
connected = true;
} else if (value == "no") {
connected = false;
} else {
connected = false;
}
}
And change the code in the angular controller to this:
detectConnexionTest();
if (connected === true) {
$scope.online = "connected";
} else if (connected === false) {
$scope.online = "not connected";
}
Try the following code, it's cleaned a bit.
function detectConnexionTest() {
var urlOnline = "/connect";
jQuery.ajax({
type: 'GET',
url: urlOnline,
success: function(data, textStatus, xhr) {
detectConnexion(true);
},
error: function(xhr, textStatus, errorThrown) {
detectConnexion(false);
}
});
}
function detectConnexion(b) {
$scope.online = b ? "connected" : "not connected";
}
detectConnexionTest();
By far the easiest way to do this is with the navigator.onLine property. You could implement the javascript to run when a button is pressed. You can put it into a simple if, else statement. Read more here:
http://www.w3schools.com/jsref/prop_nav_online.asp
Example:
function checkConnection() {
if (navigator.onLine) {
// Action
} else {
// Action
}
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
So this is my code for some ajax that I'm doing.
function check_password(){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
},
function(response) {
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
return response.indexOf('success');
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
and here I'm trying to handle the return value from the check password function.
jQuery(function() {
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
} else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
} else if (check_password() != 73) {
hasError = true;
$("#password").after(check_password());
}
if (hasError == true) {
return false;
}
});
});
For some reason the if statement is returning true even when the index(return value) is 73. I test this by using jquery within the if statement to print out the value of the returning function and it prints out 73. I have a feeling my error is caused because of dynamically typed variables in javascript.
Typical asynchronous behavior issue of AJAX calls. You return response.indexOf('success'); from your AJAX callback, but since it is an asynchronous callback, there is nothing to return to. The rest of you check_password function has long finished when the callback is being called.
To fix this you need to completely restructure your code. In your click handler, you first need to call your post() function and then in the callback you need to go through your if/else if blocks.
Your function ´checkpassword()´ doesn't actually return a value.
It launches a request to a PHP-file and immediately returns (without a value).
You do specify a callback for when the call returns, but that never gets back to your original function.
You could do something like this:
function check_password(callback){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
callback(response.indexOf('success'));
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
jQuery(function(){
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
}
else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
}
else (
check_password(function(returnValue) {
if (returnValue != 73) {
hasError = true;
$("#password").after(check_password());
}
})){
}
if(hasError == true) {return false;}
});
});
Of course, this code just shows you how to get the value inside the other function, but you still need to handle the fact that you're other function doesn't return immediately and that for example the value of HasError is not set immediately.
Your problem is that you return from within a inner function, which will never ever work in JavaScript. Pass a callback:
function check_password(callback) {
// ...
callback(response.indexOf('success'));
}
// ...
check_password(function(result) {
if(result != 73) {
// ...
}
})
Just search for JavaScript AJAX and you will find a lot of sites to study. Here is one of them: http://www.html5rocks.com/en/tutorials/async/deferred/