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

Having trouble getting CSS3 Keyframes to function properly?

Check out the following code snippet: .startanimation { height: 100px; width: 100px; background: yellow; -webkit-animation: animate 1s infinite; } @-webkit-keyframes animate { 100% { width: 300px; height: 300px; } ...

The keyboard fails to open when trying to input text on a WKWebView

Is there a way to programmatically open the keyboard in a WkWebView for tel text input after a JavaScript function call? I want the keyboard to display for efficiency reasons when a certain input is activated, but it doesn't gain focus automatically. ...

Laravel's routing system may cause complications when trying to send data via jQuery AJAX post requests

My current challenge involves passing an ID to a PHP script through AJAX. Previously, everything was working perfectly with the code snippet below: var baseURL = '/W4W/public/'; function voteUp(){ var snippetID = document.getElementById(&ap ...

Displaying JSON data from the API on a webpage within a NodeJS weather application

Currently, I am in the process of developing a weather application using NodeJS. I have successfully retrieved JSON formatted data from the weather site's API. Nonetheless, I am perplexed about how to transmit this data to the application. Below is a ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

Is there a better method to determine the width when utilizing the jQuery UI resizable feature for improved efficiency?

I'm currently working on a website that features a resizable sidebar. I want the icons and text within the sidebar to shrink proportionally when the user resizes it. Right now, I have implemented an if statement to check if the sidebar's width fa ...

Tips for implementing an automatic refresh functionality in Angular

I am dealing with 3 files: model.ts, modal.html, and modal.ts. I want the auto refresh feature to only happen when the modal is open and stop when it is closed. The modal displays continuous information. modal.htlm : <button class="btn btn-success ...

Extract information from an ajax call and convert it to a json format

I'm encountering an issue when attempting to send data from Ajax to a PHP page. While I can successfully send the data, I am facing challenges in accessing it from the PHP page. Here is my Ajax code: $http({ method: 'POST', url: & ...

Postback functionality in ASP.NET using AJAX and JavaScript technology

I want to create a simple application with one label and two drop-down lists. When a player name is selected from the first drop-down, I want the corresponding country to be displayed in the second drop-down without refreshing the whole page. Here is the c ...

Can a PHP script using sleep() function alongside AJAX return results sequentially?

Scenario: Several asynchronous calls are sent to a single .php file concurrently, each with different parameters getInfo("keyword1"); getInfo("keyword2"); getInfo("keyword3"); The php script performs a quick operation, then pauses for 2 seconds before d ...

How can we efficiently generate ReactJS Router for Links and seamlessly display a unique page for each Link?

Currently, I have an array of objects named titleUrl, which contains titles and URLs retrieved from an API. To display these as links on the sidebar, I am utilizing a custom component called MenuLink. The links are generated by iterating over the keys in t ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

How can JavaScript routes be used to apply specific code to multiple pages on a website?

Can you provide guidance on how to run the same code for multiple pages using routes? Below is an example I am currently exploring: var routeManager = { _routes: {}, // Collection of routes add: function(urls, action) { urls.forEach(fun ...

Having trouble receiving an undefined value when making an ajax call to a web service?

Whenever I make an ajax call, I keep getting an undefined value. Take a look at my code on this fiddle Link I am wondering if we can include data in json format like this: 'north': '44.1', 'south'='-9.9' , 'e ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

Unable to retrieve information from the JSON object

Here's the script I'm working with: <script type="text/javascript> function getData(username){ $.ajax({ url: '{% url "data" %}', data: { ' ...

What is the best way to add table pagination at the bottom of a table?

Can someone provide guidance on implementing table pagination for the material-ui table below? The documentation is a bit unclear: <Table ria-label="a dense table"> <TableHead> <TableRow> ...

What is the best way to transfer a file from Postman to a Node.js server using Multer?

Windows Express version 4.12.4 Multer version 1.0.1 Node version v0.10.22 I'm currently working on sending a file to my node.js server using Postman. I'm following the instructions provided in the readme here This is what I am sending wi ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

I'm having trouble getting FlowType.js to function properly

I have added the following code just before the closing </body> tag, but unfortunately, it seems like the type is not changing as expected. I am struggling to identify what mistake I might be making. Check out FlowType.JS on GitHub View the code on ...