How to await the ajax request?

How to await the ajax request?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Asynchronous Trap in Form Validation

Attempting to validate a number against a database before allowing a form submission is a common pattern, but doing it with synchronous logic in an asynchronous world leads to bugs. The core issue here isn't complex business logic; it's a fundamental misunderstanding of how JavaScript handles execution flow when dealing with network requests.

In the provided scenario, the validation() function runs immediately when the user clicks the submit button. Inside that function, loadNumRows() is called to fetch data from the server. However, the AJAX request is asynchronous. This means the browser sends the HTTP request and fires off to the server, but the JavaScript engine does not wait for the response before continuing to execute the next line of code in the current scope.

Consequently, execution moves immediately to the loop checking the text areas and finally reaches the return statement at the end of validation(). At this exact moment, the success callback for your AJAX call hasn't run yet. The variable numOfRows is still holding its initial value of 0, regardless of what the database actually returned. You are making a decision based on stale data because the asynchronous operation finished after the function already exited.

To fix this, you must ensure that the validation logic waits until the AJAX request completes before returning a boolean result. In modern JavaScript, this is achieved using Promises and async/await. By converting the AJAX call into a Promise chain or an async function, you create a synchronization point where execution pauses until the server responds.

Here is how you would refactor the code to handle this correctly:

var textAreaList;
let numOfRows = 0; 
// Note: Using 'let' allows us to reassign inside the async block if needed,
// though in this specific pattern we return early based on the result.

document.getElementById("btn_submit").onclick = validation;

textAreaList = document.getElementsByClassName("text_input");

function loadNumRows() {
    // Wrap the AJAX call to ensure it returns a Promise that resolves with the data
    return $.ajax({
        url: 'php/SeeIfNumberExists?number=' + document.getElementById('number_inp').value,
        type: "GET",
        cache: false
    });
}

async function validation() {
    // Await the AJAX request before proceeding with logic
    const response = await loadNumRows();
    
    // The data is now available in 'response' instead of 'numOfRows' 
    // directly, or you can assign it here if your backend returns JSON.
    // Assuming the backend returns a number as per the original code:
    numOfRows = parseInt(response);

    try {
        const failureElement = document.getElementById('failure');
        if (failureElement) {
            failureElement.hidden = true;
        }
    } catch(e) {
        console.log(e.message);
    }

    textAreaList = document.getElementsByClassName("text_input");
    var failValidation = false;

    for (var i = 0; i < textAreaList.length; i++) {
        if (textAreaList[i].value == "") {
            textAreaList[i].style.border = "2px solid #ff0000";
            failValidation = true;
        } else {
            textAreaList[i].style.border = "2px solid #286C2B";
        }
    }

    // Now we are returning after the data has been fetched.
    // If failValidation is true, return false immediately.
    // If numOfRows != 0 (duplicate exists), return false.
    return !(failValidation || numOfRows != 0);
}

The key change is wrapping the AJAX call in an async function and using await. This transforms the asynchronous flow into a synchronous-looking sequence from the perspective of the execution context. The code inside validation() will not reach the return statement until the server has responded and updated numOfRows.

There are trade-offs to consider with this approach. The primary one is user experience. If the number lookup takes a long time (e.g., 2 seconds), the user will see their cursor freeze on the submit button. During this time, they cannot interact with the form. A more robust application might show a loading spinner or disable the button visually while the await resolves to prevent double submissions.

Another consideration is error handling. In the original code, there was no check for AJAX failures (network errors, 404s, etc.). If the server fails to respond, numOfRows remains 0, and the form might submit incorrectly or throw an error when the DOM element isn't found. Always wrap your await calls in a try...catch block to handle these scenarios gracefully.

This pattern is essential for any application performing validation against external services. While you can solve this using callbacks ($.when()), modern syntax makes the intent much clearer and reduces nesting levels. If you are building a larger Laravel application, consider utilizing Laravel's built-in validation classes which can sometimes offload this complexity to the server side entirely, ensuring data integrity before it even hits your JavaScript logic.

Our network