I have a wizard/form using JQuery Steps to add a customer to our internal website and I need to validate an email/telephone/name server side to check for preexisting customers. PHP returns the number of matches. If they don't exist, JQuery Steps has an onStepChanging event which needs a return value of true to allow it to proceed to the next 'step' (it naturally returns false).
I have used 'async:false'
in my Ajax request, which works, but I get a warning about it being deprecated and in this instance, I need it to run synchronously. I want to do it properly and follow best practice especially if 'async:false' does get deprecated. Apparently, it will be deprecated in order to improve user experience by not freezing processes.
If I remove 'async:false', then when I call my checkExisting(), I will always get 0 returned because it won't update my 'matches' variable since it's running asynchronously, and I understand this but I need to return the number of matches.
I've tried altering my ajax and returning ajax1, then doing
checkExisting(..).done(function(){... return true})
but this doesn't seem to work either and returns [object Object]
. It returns me out of the .done() but doesn't pass this return true/false to the onStepChanging:function(){...}
Normally, I would do something along the lines of
validateThing().done(function() {
// if invalid, add a red border around the input
// add validation message
});
I have read several answers and they seem to suggest restructuring your code to improve the user experience. Some suggested to return the ajax and using .done() or .then(). However, I'm bound to this onStepChanging event in jQuery Steps and I need to return true/false.
// this is what currently works with async:false
function checkExisting(email) {
let matches = 0;
let ajax1 = $.ajax({
url: "/includes/pages/organisations/ajax.php",
type: "GET",
async: false,
data: {action: 'checkExisting', value: email},
success: function(response) {
const responseData = JSON.parse(response);
matches = responseData.matches;
}
});
return matches;
}
// JQuery Steps
$('#addNewCustomer').steps({
onInit: function() {},
onStepChanging: function(e,currentIndex, newIndex) {
let stepStatus = false;
if(checkExisting(customer.email) === 0) {
// customer exists
stepStatus = true;
} else {
// add validation error message
// add validation styling
}
return stepStatus;
}
...
});
I need to be able to call checkExisting() and have it return a number. I can then use this to return true/false to JQuery Steps, and I can also use it to report the number of matching customers in the validation message ("3 customers exist with this number").
Apologies if I'm being incredibly dense and I'm missing something obvious!
Thanks for your time.