What causes the return value of an ajax request to be undefined when using setTimeout? How can this issue be resolved?

When the HTML body loads, I have two separate AJAX functions that need to be called. These functions should operate at different time intervals for different types of chat in order to distribute the server workload effectively. (No JQuery, please)

function executePOST(data1, data2) {
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function(){
        //Appending xml data to html in a loop
    }
    var date = new Date();
    var datetime = date.getTime();
    xmlhttp.open("POST", "page1.php", true);

    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    var parameters = "data1="+data1+"&data2="+data2;
    xmlhttp.send(parameters);
}

function executeGET(data1, data2) {
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function(){
        //Appending xml data to html in a loop
    }
    var date = new Date();
    var datetime = date.getTime();

    xmlhttp.open("GET", "page2.php?datetime="+datetime, true);

    xmlhttp.send();
}

Each AJAX function works fine individually, but issues arise when trying to nest or schedule them at specific intervals.

function nestedExecution(data1, data2) {
    executePOST(data1, data2); 
    executeGET(data1, data2);
}

OR

function scheduledExecution(data1, data2) {
        setTimeout( function(){
            executePOST(data1, data2); 
        }, 10000);
        //Run every 10 seconds
        setTimeout( function(){
            executeGET(data1, data2);
        }, 60000);
        //Run every 60 seconds
    }

Only the second AJAX call within the nesting executes, regardless of their order, and an error is returned for the first function.

TypeError: The return value of the AJAX "XML" is undefined.

This seems inaccurate as they work perfectly on their own.

The only workaround was placing them inside timed functions, but this prevented the first function from running every 10 seconds.

function mixedExecution(data1, data2) {
        setTimeout( function(){
            executePOST(data1, data2); 
            setTimeout( function(){
                executeGET(data1, data2);
            }, 60000);
        }, 10000);
    }

Answer №1

Each of your functions is using a common global variable named xmlhttp. To prevent conflicts, declare this variable separately within each function using the var keyword:

var xmlhttp;

The issue right now is that when one function is called, it overwrites the value of xmlhttp set by another function. By creating two local variables instead, this problem can be avoided.

A helpful practice to identify such problems (especially in newer browsers) is to include

"use strict";

as the first line of code within each function or preferably at the beginning of the entire script block. Enabling "strict" mode in the interpreter would have detected the incorrect assignments to xmlhttp.

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

Retrieving, storing, and utilizing JSON variables in Express

I've been struggling to grasp the concept of accessing and processing data using different HTTP methods like get, put, post. Currently, I have managed to retrieve JSON data and store it in a global variable. var pokemonsData; fetch('https://raw ...

What makes websockets too complex for basic applications?

Source: It is mentioned that a WebSocket connection is designed to be persistent, which could be unnecessary for simpler applications. For example, when referring to socket.io, which acts as a wrapper around websockets and simplifies the setup process, ...

Executing an Ajax request. Best method for transmitting various data elements:

I am currently attempting to perform an ajax call with multiple data inputs. When I send only one string of data, I use the following method: $.ajax({ url: "php/update_lastordning.php", type: "POST", data: "elId=" + elId }); To retrieve t ...

Python automation with selenium - capturing webpage content

I am utilizing selenium to scrape multiple pages while refraining from using other frameworks such as scrapy due to the abundance of ajax action. My predicament lies in the fact that the content refreshes automatically nearly every second, especially finan ...

The jQuery AJAX request consistently triggers the success event

I have been working on a login form that undergoes server-side validation, and now I am attempting to implement jQuery validation as well. Here is a snippet of the form: <div class="form-actions"> <button type="submit" class="btn green pull ...

What is the proper way to execute a JavaScript function within a JavaScript file from an HTML file?

I have the following content in an HTML file: <!DOCTYPE html> <!-- --> <html> <head> <script src="java_script.js"></script> <link rel="stylesheet" type="text/css" href="carousel.css"> & ...

Placing divs of varying heights in a circular formation with a specific radius

Recently, I've been attempting to generate a multitude of divs (referred to as bars) and position them in a way that forms a circle in the center. To clarify, here's an example where all bars share the same width and height. Check out the JSFi ...

show button after the page has finished loading

I have a button similar to this: <input type="submit" id="product_197_submit_button" class="wpsc_buy_button" name="Buy" value="Add To Cart"> However, I am encountering an issue where if the user clicks the button before all scripts are loaded, an e ...

Resolve the ajax issue and retrieve TCPDF after the server post

I am encountering an issue when trying to generate a TCPDF after validating a form. If the validation fails, the PHP file returns an error message. However, if the validation is successful, I want to return the PDF. The problem is that when the PDF is retu ...

Adding a service into a different service within AngularJS

I'm trying to add a login module to my AngularJS app. When I try to call UserService from the authenticationService, it's showing as undefined. What am I missing here, why is UserService coming up as undefined? var authenticationService = angula ...

Utilizing Angular Dependency Injection for Extending Base Services with Subclasses

My service setup includes a base service and two services that inherit from it: @Injectable({ providedIn: 'root' }) export class BaseService { foo(src?: string){ return `speaking from ${src || 'BaseService'}`; } } @Injectable ...

Getting the initial date of the upcoming month in JavaScript

I'm trying to figure out how to get the first day of the next month for a datePicker in dd/mm/yyyy format. Can anyone help? Here's the code I currently have: var now = new Date(); if (now.getMonth() == 11) { var current = new Date(now.getFu ...

Obtain the identifier of a specific row within a table using the response.write method in ASP.NET with C#

Currently, I am facing an issue with my Ajax function that utilizes a Server page. The problem arises when implementing paging on the server page. I have generated a table on the server page using response.write method. protected void Page_Load(object ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...

Issue with Ajax sending undefined variable to PHP index

Is it possible to display the variable num in a php page? An error message is appearing: Notice: Undefined index: num in C:\xampp\htdocs\javas.php on line 4 Here is the PHP code snippet: <?php $lol = $_POST['num']; echo " ...

Encountering a TokenMismatchException when using javascript x-editable in Laravel 5.3

Despite trying various solutions from different sources, such as SO, none of them were able to resolve the issue before marking it as duplicated. Currently, I am utilizing the x-editable plugin to save a new record through a store route. After submitting ...

What is the best way to showcase the properties of multiple files with the help of

I have been attempting to utilize jQuery to exhibit the specifics of several uploaded files. Below is my code: <!DOCTYPE html> <html> <head> <title>jQuery Multi File Upload</title> </head> <body> <f ...

What is the most effective way to set up HTTPS for handling all connections in Node.js?

In my project to create a stateless authentication system using Double Submit Cookie in Node.js/ExpressJs, I am exploring ways to ensure all connections are made over HTTPS. My goal is to optimize for handling high traffic while also prioritizing security ...

Tips for resolving the UNABLE_TO_GET_ISSUER_CERT_LOCALLY issue while attempting to install Sentry using npm or curl

https://i.stack.imgur.com/G8hfZ.png curl -sL -k https://sentry.io/get-cli/ | bash Even though I've specified not to verify the certificate with -k, I'm still facing issues trying to install it. The script is supposed to automatically install sen ...