The event is eagerly anticipating the AJAX call despite the asynchronous setting being true

I'm implementing a feature where the user can open a new tab to continue using the system while the current tab is busy making a request to the server.

To achieve this, I am trying to utilize $(window).load() or $(window.document).ready() to automatically click on an element once it's ready. However, during testing with a substantial server request, the window only loads after the ajax request completes and the success function finishes executing, despite being asynchronous. I would appreciate any insights into why this behavior is occurring.

g_SearchHandler.SearchPleaseWait(true);
initiates a loading animation overlay on the screen and triggers the function displayNewTab() which opens the new tab.

Snippet to open new tab:

displayInNewTab: function(){
        try {
            var w = window.open(href = "/prod/php/home.php");
            var loadingFunc = function(){
                var devices = w.document.querySelector(`.sidebar-segment[data-segment-name="DEVICES"]`);
                var selDevice = getSelectedDeviceTreeData();
                if(!selDevice){
                    return;
                }
                var selDeviceObj = w.document.getElementById(selDevice.name);
                // Keep attempting to click on elements once they become available
                if(devices && selDeviceObj){
                    devices.click()
                    w.ClickOnItem(selDevice.name, false, true)
                }else{
                    setTimeout(loadingFunc,1000);
                }
            }
            $(w.document).ready(loadingFunc);
        }catch (e){
            console.error(e)
        }
    }

g_SearchHandler.SearchPleaseWait(true); Ajax request:

$.ajax({
        type     : "POST",
        dataType : "json",
        url      : "commands.php",
        data     : params,
        success  : function(objJSON)
        {
            DisplayResults(objJSON);
            g_SearchHandler.SearchPleaseWait(false);
        }
});

Answer №1

It appears that the delay occurred because the page needed extra time to request resources from the server. As a result, the server prioritized serving the ajax request first, placing the request for page resources in a queue and fulfilling it after the ajax request was processed.

A temporary solution was to use setTimeout() to ensure that the new page would request resources before sending the ajax request.

For example:

setTimeout(function(){
    $.ajax({
        type     : "POST",
        dataType : "json",
        url      : "commands.php",
        data     : params,
        success  : function(objJSON)
        {
            DisplayResults(objJSON);
            g_SearchHandler.SearchPleaseWait(false);
        }
    })
},5000);

EDIT

After recognizing the root cause of the issue, I explored better solutions.

Two alternatives were considered:

1. Fetch the page resources before opening the tab and then proceed with the ajax request:

$.get("/prod/php/home.php")
    .done(function(){
        // Open new tab with fetched resources.
        // Make ajax call here.
    })
  1. Another effective solution involved resolving the locked PHP session by using session_write_close(); on the server side.

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

I am in search of a way to utilize JavaScript in order to transform a "flat" JSON object into a nested JSON tree that allows for a one-to-many matching capability

I'm on a mission to transform a flat JSON object into a nested tree using JavaScript. The unique challenge I'm facing is the need to match one child node to multiple parent nodes, a scenario I haven't found in existing solutions. Behold, my ...

Stop Swiper Slide from moving when clicked on

I am currently utilizing Swiper JS and have encountered an issue. In my Swiper slider, each slide contains a button. Whenever I click on the slide or the button itself, the slide becomes the active one, causing the entire slider to move. Is there a way to ...

Conducting various calculations and showcasing them all on a single webpage

Uncertain about what to name this, but let's see if you understand my question. I have a table on a standard HTML page and I am performing some calculations using Javascript/jQuery. Example: function addThem() { var result; result = userIn ...

Navigating with NestJs without utilizing response usage

Can a redirect be initiated from a Nest controller without involving the use of the @Response object? Currently, the only method I'm aware of is through direct injection of the @Response object into the route handler. ...

The attempt to run 'setProperty' on 'CSSStyleDeclaration' was unsuccessful as these styles are precalculated, rendering the 'opacity' property unchangeable

I am attempting to change the value of a property in my pseudo element CSS class using a JavaScript file. Unfortunately, I keep encountering the error mentioned in the title. Is there any other method that can be used to achieve this? CSS Code: .list { ...

Switching out one block of HTML with another in JavaScript is a powerful way to dynamically update

I am working on creating a feature on a webpage where clicking a button will change the HTML code inside a specific div. Essentially, I want to be able to update the content of a div by simply clicking a link. Here are two different sets of HTML code: Co ...

Exploring Variable Naming in Angular with Dynamic Scope

Is there a way to avoid using large IF statements in my controller when working with fields/models that have similar logic but different scope variable names? I'm looking for a solution to dynamically append numbers to the scope variable names in Angu ...

react function for class activation

Can you guide me on how to trigger the activation of the element's class when clicking the 'Next' button? The goal is for the styles to change upon clicking a specific class. Any advice on integrating this functionality within the provided f ...

The function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

Is it standard for Express middleware to execute for each imported .js file?

I recently set up an express application that serves a static file from a directory named public. Within the public directory, there are 3 files: "index.html", "script1.js", "script2.js", and "script3.js". The script files are currently empty .js files. ...

Encountering "Cannot write file" errors in VSCode after adding tsconfig exclude?

When I insert the exclude block into my tsconfig.json file like this: "exclude": ["angular-package-format-workspace"] I encounter the following errors in VSCode. These errors disappear once I remove the exclude block (However, the intended exclusion fu ...

Detecting changes in arrays in Vue.js 2

Below is a simplified version of the code : <template> /* ---------------------------------------------- * Displaying a list of templates, @click to select the template /* ---------------------------------------------- <ul> ...

Identifying the previous slide in a Bootstrap 4 Carousel

Imagine I'm on slide 9 and navigate to slide 8 using the link below: <a class="carousel-control-btn" href="#Carousel" role="button" data-slide-to="8"> Now that I'm on slide 8, is there a method to identify the previous slide I came from? ...

Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango" let fruitArray = [{fruit:"apple",locale:"US"}, {fruit:"orange",locale:"US"}, {fruit:"banana",locale:"US"}, {fruit:"apple",locale:"US"}, {fruit:"orange",locale:"IT"}, {fruit:"apple",locale: ...

Having trouble retrieving the innerHTML of a span tag in a JavaScript function

I'm currently working on creating an email message that will have pre-filled text from an asp:Literal when a user clicks a link. The HTML code for this is structured like this: <tr> <td> <img src="../../images/Question.gif" ...

Angular 5 combined with the dynamic capabilities of Popper.JS

Launching a training project that requires Popper.Js in its features has been quite challenging. Despite following Bootstrap's documentation on how to implement Popper.Js, I have encountered difficulties. As per Bootstrap's docs, I tried initiat ...

A guide on customizing the appearance of individual items in a vue v-for loop based on specific conditions

I am currently developing a multiple choice quiz game and I want the selected answer by the user to change color, either red or green, depending on its correctness. To achieve this, I have created a variable called selected that correctly updates when the ...

Utilizing function arguments in ReactJS

Currently, I am in the process of learning ReactJs and have an inquiry about the code snippet below. Would someone be able to clarify the functionality of the removeTour code and why the id parameter is being used within the function? const removeTour = (i ...

Implementing a scrolling feature in the autocomplete textbox to handle lengthy data

I successfully implemented an autocomplete multiselect textbox functionality that is working well. However, I am facing an issue with a long list of values appearing when I have 3000 records and type A in the textbox. Please refer to the screenshot below: ...

Having trouble loading JSON api data in React?

Recently, I've delved into the world of React and was assigned a task to fetch data from a JSON API and showcase it on the screen. Initially, everything went smoothly while practicing with this URL - https://jsonplaceholder.typicode.com/users. Howeve ...