Is it feasible to utilize the return value of an Async call to display or conceal an alert message?

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;
}

Answer №1

If you're looking to improve your JavaScript skills, consider exploring async/await functionality:

function checkButtonClick(){
          validateDate()
                  .then(result => {
                       if (!result)
                           //display confirmation dialog
                   })
                  .catch(err => //handle error);
     
}

async function validateDate(){
      var isValid = false;
      //perform AJAX request with await keyword
      isValid = await fetch(url);
      return isValid;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transitioning images in JQuery by using a rollover effect

Is there a way to use Jquery for a hover effect that transitions images with a slide up animation? I've looked everywhere online, but I can't seem to find a code that works. All the examples I've found use fadeIn or fadeOut. Thank you for yo ...

Troubleshooting issue with parsing MySQL data in HTML table using Node.js

Seeking Assistance! I am currently in the process of developing a node file that displays data from MySQL on an HTML page with a search bar. My issue is that sometimes when I run the code, enter something into the search bar and hit the button, it works s ...

The Vue.js application is failing to toggle the integrated code

I am new to using Vue and I am trying to create a vertical navigation bar. When the menu icon is clicked, the navbar should toggle. Here is my menu icon code: <button type="button" id="sidebarCollapse" class="btn btn-info [collapsed?'': ...

Can one transition from using a callback to a returning Promise in order to implement an ErrorFirstCallback strategy?

In Node.js documentation, it is explained that an ErrorFirstCallback is triggered when the referred function fails. Error-first-callbacks in Node.js I have been practicing with this callback pattern and I am curious to know if it is possible to refactor i ...

Using the spread operator in ES6 allows for arguments to be placed in a non-con

When working in nodeJS, my code looks like this: path = 'public/MIN-1234'; path = path.split('/'); return path.join( process.cwd(), ...path); I was expecting to get: c:\CODE\public/MIN-1234 but instead, I got: `‌publ ...

The putImageData function claims that the given object is not an ImageData object, but upon inspection in the console, it clearly displays that it is

After using getImageData to store the pixels of an image in a two-dimensional array, I attempted to draw them with putImageData. However, I encountered an error indicating that the first parameter is not of type ImageData. Strangely, when I logged the vari ...

Choose the current parent item using Angular's ng-selected and $index

http://plnkr.co/edit/fwwAd4bn6z2vxVN2FUL7?p=preview On the Plunker page linked above, I am trying to achieve a specific functionality. I would like the 3 dropdown lists to display values A, B, and C initially. When a 4th dropdown option is added, it shoul ...

Executing a Javascript function repeatedly

Here is a sample JavaScript function: function f1() { alert("HI"); } I have two different locations where I am calling the same JavaScript function: <input type="submit" id="btn1" onclick="f1()"/> <input type="submit" id="btn2" onclick="f1 ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

Tips for resolving a jspdf naming collision situation

In my react app, I am utilizing various jsPDF libraries as shown below: For exporting tables as HTML: import jsPDF from 'jspdf'; import "jspdf-autotable"; For converting SVG to PDF: const svg2pdf = require('svg2pdf.js'); con ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...

I aim to continuously refresh a dynamic canvas line chart with JSON data

Having trouble with my code - the chart isn't updating. I'm new to using canvasJS charts and could use some help. <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ page import=”java ...

Guide on altering the cell's background hue depending on its value through javascript

I'm dealing with a table that has 3 columns: field1 is a Category field2 and field3 contain Measures (specifically integers 1, 2, 3, 4, and 5). Is there a way to use Javascript to conditionally format the background color of cells in the table hol ...

Encapsulate ng-style within quotation marks

I am trying to hide a span if the value of filters[*index*] is empty. var span = "<span ng-style='{ 'display': filters[" + filterIndex + "] == '' ? 'none' : 'inline-block' }'></span>" cell.html ...

The scrollTop feature fails to function properly following an Axios response

I'm currently facing a challenge with creating a real-time chat feature using Laravel, Vue.js, Pusher, and Echo. The issue arises while implementing the following 3 methods: created() { this.fetchMessages(); this.group = $('#group') ...

Retrieving the chosen item from an unordered list using jQuery

Hello, I am currently populating a list using the ul-li HTML tags dynamically. My goal is to retrieve the value of the selected li within the corresponding ul. Despite trying various jQuery methods, I keep getting 'undefined'. Here is how I popul ...

converting HTML values to TypeScript

I'm a beginner with Angular and could use some assistance. Currently, I have two components - one for the index and another for navigation. Within the index component, there are subcomponents that change based on the value of a variable called produ ...

Effortless document uploading and visualization

I am currently utilizing the express-fileupload package for image uploads. The uploaded images are stored in my local directory. My goal is to include the filename in the MongoDB database if possible and then display the image on the frontend of my applica ...

What is the best way to configure input fields as readonly, except for the one being actively filled by the user

Is there a way to make all input fields readonly except the one that the user is trying to fill data into? After the user loads the page index.php and attempts to input data into, for example, <input id="edValue2" ...>, I want to set all input field ...

React - Exploring the depths of functional components

Picture this: a straightforward form that showcases several unique components with customized layouts. The custom components include: <UsernameInput />, <PasswordInput />, <DateTimePicker />, <FancyButton />, <Checkbox /> Th ...