Executing Javascript and AJAX code only yields anticipated results after being run more than once

Here are two methods that check the availability of a person for each day within a specified date range. These methods use two variables: one to count the total days between the start and end dates (dayCount) and the other to track the number of available days for the person (validDays).

If these two variables are not equal, an error message is displayed indicating that the person is not available.

The checkAvailable() function invokes the setAvailable() function, which in turn makes an AJAX call to verify the availability of the person on a particular date. The AJAX call returns either true or false, and this process works correctly.

The problem I'm encountering is that I have to click the button twice before the dayCount and validDays variables display the correct values. For example, if I select a PM booking, knowing that the person is available during that time, the first click on the button shows "Unavailable," while subsequent clicks correctly show "Available."

I initially thought the issue was related to asynchronous processes not completing before comparing the two variables, but upon adding some delays for verification, it seems like that's not the cause.

Javascript code:

var validDays = 0;

function checkAvailable() {

    event.preventDefault();

    var teacher = $("#selectedTeacher").val();

    var startDate = new Date($("#startDate").val());
    var endDate = new Date($("#endDate").val());
    var dayCount = 0;

    // Loop through each day
    for (var day = startDate; day <= endDate; day.setDate(day.getDate() + 1)) {
        console.log('date: ' + day);
        var duration;
        var starttime;
        var endtime;

        var dayOfWeek = day.getDay();

        var monday = document.getElementById('enableMon');
        var tuesday = document.getElementById('enableTue');
        var wednesday = document.getElementById('enableWed');
        var thursday = document.getElementById('enableThu');
        var friday = document.getElementById('enableFri');

        if (dayOfWeek == "1" && monday.checked) {
            duration = $("#DurationMonday").val();
            starttime = $("#startTimeMon").val();
            endtime = $("#endTimeMon").val();

            console.log('Add 1 to day count - ' + dayCount + '. Valid days are - ' + validDays);
            setAvailable(teacher, day, duration);
            dayCount++;
            console.log('Day count is now - ' + dayCount + '. Valid days are - ' + validDays);
        }
        else if (dayOfWeek == "2" && tuesday.checked) {
            duration = $("#DurationTuesday").val();
            starttime = $("#startTimeTue").val();
            endtime = $("#endTimeTue").val();

            console.log('Add 1 to day count - ' + dayCount + '. Valid days are - ' + validDays);
            setAvailable(teacher, day, duration);
            dayCount++;
            console.log('Day count is now - ' + dayCount + '. Valid days are - ' + validDays);
        }
        else if (dayOfWeek == "3" && wednesday.checked) {
            duration = $("#DurationWednesday").val();
            starttime = $("#startTimeWed").val();
            endtime = $("#endTimeWed").val();

            console.log('Add 1 to day count - ' + dayCount + '. Valid days are - ' + validDays);
            setAvailable(teacher, day, duration);
            dayCount++;
            console.log('Day count is now - ' + dayCount + '. Valid days are - ' + validDays);
        }
        else if (dayOfWeek == "4" && thursday.checked) {
            duration = $("#DurationThursday").val();
            starttime = $("#startTimeThu").val();
            endtime = $("#endTimeThu").val();

            console.log('Add 1 to day count - ' + dayCount + '. Valid days are - ' + validDays);
            setAvailable(teacher, day, duration);
            dayCount++;
            console.log('Day count is now - ' + dayCount + '. Valid days are - ' + validDays);
        }
        else if (dayOfWeek == "5" && friday.checked) {
            duration = $("#DurationFriday").val();
            starttime = $("#startTimeFri").val();
            endtime = $("#endTimeFri").val();

            console.log('Add 1 to day count - ' + dayCount + '. Valid days are - ' + validDays);
            setAvailable(teacher, day, duration);
            dayCount++;
            console.log('Day count is now - ' + dayCount + '. Valid days are - ' + validDays);
        }
    }

    if(dayCount == validDays)
    {
        toastNotifySuccess("Available", 2000);
        $("#btnSave").attr('disabled', false);
    }
    else
    {
        toastNotifyError("The selected teacher is not available", 2000);
        $("#btnSave").attr('disabled', true);
    }

    dayCount = 0;
    validDays = 0;
};

async function setAvailable(teacher, day, duration) {

    return await $.ajax({
            url: '/Availability/CheckAvailabilityForDate?teacher=' + teacher + '&date=' + day.toISOString() + '&duration=' + duration,
            type: 'POST',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                if (response == false) {

                }
                else if(response == true) {
                    console.log('add 1 to valid days - ' + validDays);
                    validDays++;
                    console.log('added 1 to valid days - ' + validDays);
                }
            }
        });
};

MVC:

[HttpPost]
    public async Task<string> CheckAvailabilityForDate(int teacher, DateTime date, BookingDuration duration, DateTime startTime, DateTime endTime)
    {
        bool available = true;

        available = await _availabilityService.CheckAvailable(date, teacher, duration, startTime, endTime, null);

        return JsonSerializer.Serialize(available);
    }

Answer №1

Make sure to include the await keyword in your code. By omitting it, you initiate the request without waiting for a response. If you call the method again, chances are the request has completed and you'll get the correct validDays.


async function checkAvailability { // don't forget async
...
    await setAvailability(teacher, day, duration); // remember await here
...
}

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

Exploring the possibilities of jQuery UI sortable alongside container zoom functionality

Is there a way to sort divs within a container that has a zoom of 0.4 while maintaining the position relative to the mouse cursor when dragging? I am facing an issue where the dragged div does not move in sync with the cursor when sorting elements within ...

Adjusting the width of the search bar in a Bootstrap inline form

Issue: The search box is not resizing with the page and I can't figure out how to make it wider. Adding styles like width: 100%; hasn't worked so far. In addition, the select dropdown box in the image linked below appears slightly clipped on the ...

Browse through content without displaying the page title on the navigation bar and without the use of frames

When I sign into certain websites, I have noticed that the address displayed is often something like this: https://examplesite.com/access Even though all the links on the landing page are clickable and functional, their corresponding addresses never show ...

Unable to assign a value to an indexed property in 'FileList': Setter function for index properties is not enabled

angular.module('myApp') .directive('fileModel', ['$parse', 'uploadService','messageService','CONF', function ($parse, uploadService,messageService,CONF) { return { restrict ...

Include draggable functionality to a seating chart that is generated dynamically

I developed a function that generates table seats dynamically with equal spacing. The issue arises when I try to drag names from a list and drop them onto the seats as children. Unfortunately, I can't seem to achieve this functionality with the dynami ...

What is the best way to generate a circle around a specific point on the map without using a predetermined radius centered on a marker?

If I want to modify the code to respond to a click instead of creating a circle around a predefined marker, what changes can I make? Here is the code sample: https://developers.google.com/maps/documentation/javascript/examples/circle-simple <scri ...

Filter out all elements that come before the comma in the sorted array's output

Looking for a solution to modify my code so the output is just "Bothell" without the comma and count part. let As = document.getElementsByTagName('a'); let towns = new Map(); for(let a of As) { let town = a.textContent.split(',') ...

Here are some steps for generating a non-integer random number that is not in the format of 1.2321312312

I am looking to create random numbers that are not integers, for example 2.45, 2.69, 4.52, with a maximum of two decimal places. Currently, the generated number includes many decimal places like 2.213123123123 but I would like it to be displayed as 2.21. ...

Utilizing jQuery's nextUntil() method to target elements that are not paragraphs

In order to style all paragraphs that directly follow an h2.first element in orange using the nextUntil() method, I need to find a way to target any other HTML tag except for p. <h2 class="first">Lorem ipsum</h2> <p>Lorem ipsum</p> ...

Issues with testing incorporating jest, react, webpack, and SVG

I recently delved into the world of React development, but I've hit a snag when trying to run a test with an SVG file. You can find the code in my GitHub repository https://github.com/alejomongua/react-playground. Upon running npm run test, I encoun ...

The process for 'node app' freezes within a gulp function

When running this gulp task, it seems to hang on the exec('node config/app') line. The first exec call works without any issues, but the second one hangs indefinitely. gulp.task('test', function(cb) { var exec = require('child ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

Converting HTML text to a JavaScript array is causing issues with my code

I am currently attempting to transfer data from a PHP array to a JavaScript array without the use of additional extensions. So far, I have successfully managed to dump the ID and titles of the text items fetched from the database. However, when I attempt t ...

What is the best way to obtain the accurate URL for an MVC action when utilizing Jquery/AJAX?

Currently, I am developing my first MVC2 website and I want to incorporate AJAX into it. However, I am facing a challenge in obtaining the URL for the action while passing a URL parameter. For example, most examples demonstrate developers passing strings l ...

Troubleshooting React hooks: Child component dispatches not triggering updates in parent component

I've been trying to implement a method of passing down a reducer to child components using useContext. However, I encountered an issue where dispatching from a child component did not trigger a re-render in the parent component. Although the state ap ...

Tips for accessing a DOM element's ::before content using JavaScript

Is there a way to retrieve the content of a DOM element's ::before pseudo-element that was applied using CSS3? I've attempted several methods without success, and I'm feeling very confused! // https://rollbar.com/docs/ const links = docum ...

Combining Sails.js and Angular 2: A Powerful Integration

Trying to incorporate Angular 2 into a Sails Js application, I find myself facing some challenges as a newcomer to both. Following the official tutorial, everything works smoothly in standalone mode with a static http server. However, integrating it into t ...

What is the best way to eliminate a duplicate key-value pair from a JSON array?

Consider the following JSON data: [{"name": "John", "id": 1}, {"name": "Don", "id": 2}, {"name": "Tom", "id": 3}, {"name": "NewJohn", "id": 1}, {"name": "Tim", "id": 4}] I'm looking to determine if the key "id" has duplicate values. If duplicate ...

I'm having trouble getting my jsonp to function properly. Can anyone help me troubleshoot?

I've been working on my website for the past two weeks, learning HTML, CSS, and a bit of JavaScript. However, I'm facing an issue with the following code that I can't seem to resolve: <head> <script src="http://ajax.googleapis.com/ ...

Updating databases with the click of a checkbox

Currently, I am developing a program for monitoring cars as part of my thesis. My current focus is on user management, and I have come across an issue where the database needs to be updated when the status of a checkbox changes. To visualize checkboxes, y ...