Before this gets closed as a duplicate, I have searched through numerous threads on the forum that do not address my specific question. Please take the time to read.
Here is the scenario: when a user clicks a button, JavaScript needs to validate whether the input date is valid or not. If it's not valid, a confirmation box should be displayed giving the option to proceed with the invalid date for server insertion or update, or cancel and make edits.
In order to perform the date validation, I need to call a web method. Using an AJAX call poses challenges because it is asynchronous and does not wait for the result of the web method. Setting the variable to false initially in the "isDateValid" method causes it to always return false and display the confirmation box even if the date is actually valid (as indicated by the web method returning true). Despite implementing a callback function to handle the web method call, the message box appears before the web method response is received. The only workaround I seem to find is to make this a synchronous call instead of asynchronous. Is there a way to make it wait without setting async to false? While this logic requires synchronicity, popular advice suggests avoiding synchronous calls; hence, I am open to new approaches.
function buttonClick(){
if (!isDateValid())
// Display the confirmation box
}
function isDateValid(){
var isDateValid = false;
// AJAX call to web method
}
--- Additional details: despite attempting various solutions found online, the issue persists.
When the user clicks the "Post" button, the system should check if the date is valid. If not, a message box should appear allowing the user to proceed with posting or cancel.
function checkPostConfirmation() {
if (!checkDateValidation())
// Show confirmation box
else
// Perform different action
// Currently always lands here due to lack of "waiting"
}
// This method does not truly "wait"
async function checkDateValidation() {
let result = await isChequeDateInvalid();
return result;
}
async function isDateInvalid() {
var isDateValid = false;
var selectedDate = (obtained from control on the screen)
var result = await $.ajax
({
...typical stuff
async: true,
success: function(msg) {
callback(msg.d);
}
});
}
function callback(boolResult) {
isDateValid = boolResult;
}
return isDateValid;
}