Performing Ajax requests in a for loop without using jQuery

I am encountering an issue with a for loop that invokes an AJAX method

function clearContainerTable()
{
    var caf =  document.getElementById('CAF').value;
    var containerToAddTable = caf.split("#"); 
    for (var i = 0; i < containerToAddTable.length; i++) {
        if(!checkIfContainerBelongsToClient(containerToAddTable[i]));
            removeContainer(containerToAddTable[i]);
    };

}

function checkIfContainerBelongsToClient(serialNumber)
{
    var e = document.getElementById("id_client");
    var clientId = e.options[e.selectedIndex].value;
    var xhr = getXhr();
    var res = 12;
    xhr.onreadystatechange = function()
    {

        if(xhr.readyState == 4 && xhr.status == 200)
        {
            if(xhr.responseText == "0")
                return false;
            else if(xhr.responseText == "1")
                return true;
        }

    }
    xhr.open("GET","index.php?option=com_tkcontrack&controller=facture&task=checkIfContainerBelongsToClient&refContainer="+serialNumber+"&client_id="+clientId,true);
    xhr.send();


}

If I alert the xhr.responseText, I get "1". However, when I alert the result in the clearContainerTable method, I always get "Undefined"

Could anyone offer any assistance?

Answer №1

To enhance your code, consider making the following adjustments:

function emptyContainerTable()
{
    var caf =  document.getElementById('CAF').value;
    var tabContainerToAdd = caf.split("#"); 
    for (var i = 0; i < tabContainerToAdd.length; i++) {
        checkContainerBelongsToClient(tabContainerToAdd[i], 
            function() 
            { 
                alert('true');
            },
            function()
            {
                alert('false');
                removeContainer(tabContainerToAdd[i])
            }
         );
     }
}

/* callbackIfTrue and callbackIfFalse should be two separate functions 
   that will be executed depending on the outcome of the
   ajax call - true or false.
*/
function checkContainerBelongsToClient(serialNumber, callbackIfTrue, callbackIfFalse)
{
    var element = document.getElementById("id_client");
    var idClient = element.options[element.selectedIndex].value;
    var xhr = getXhr();
    var result = 12;
    xhr.onreadystatechange = function()
    {

        if(xhr.readyState == 4 && xhr.status == 200)
        {

            if(xhr.responseText == "1")
                callbackIfTrue();
            else
                callbackIfFalse();

        }

    }
    xhr.open("GET","index.php?option=com_tkcontrack&controller=facture&task=checkContainerBelongsToClient&refContainer="+serialNumber+"&id_client="+idClient,true);
    xhr.send();


}

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 with my router in the express app - the .find and .findByID methods are not working properly. Also,

In my current setup with NextJS/MERN stack, I am using the server.js file in NextJS to import API routes and make API calls. The routes seem to be functioning properly as there is activity when calling them from Postman or the browser. However, it appears ...

Utilizing ID's within a jade template embedded within a P HTML element

Using the jade template, I successfully formed this paragraph. My next step is to add an ID or a class around the word stackoverflow. How can I achieve this in jade? I am aware that in regular HTML we would use something like <div class="className"> ...

Generate gradient background for the chart using Vue and ChartJS by accessing the canvas context within a child component

I'm facing an issue in giving my chart a gradient background color because I cannot access the canvas context since my chart is rendered within a wrapper component that I developed. Here is the desired outcome: https://i.sstatic.net/RdXEu.png The cu ...

What could be causing my middleware to run twice?

A custom middleware was created in express.js/node.js to handle session checking. If a user ID is found in the session, it displays the user's menu; otherwise, it shows the default menu. For every page request, an ID check is performed and the user d ...

Struggling to get Redux state to update an array

I'm encountering an issue with my redux implementation in React for the first time. I've successfully utilized it for logging and registering users, but now I'm facing a challenge with fetching an array of objects from the backend using axio ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

ScriptManager throwing System.FormatException

I have implemented a ScriptManager in my ASP.NET page: <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> However, every time I rebuild my page (loading the assemblies), an error occurs: [FormatException: String was n ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Using socket.io and express for real-time communication with WebSockets

I'm currently working on implementing socket.io with express and I utilized the express generator. However, I am facing an issue where I cannot see any logs in the console. Prior to writing this, I followed the highly upvoted solution provided by G ...

View search results dynamically while typing on ASP.NET

I currently have a textbox and a literal control on my webpage. Each time a user inputs search text into the textbox, HTML code containing the search result is generated in the background and is then appended to the literal control. Now, I am attempting t ...

The challenges and benefits of using jQuery for background positioning compared to CSS animation positioning

I am currently developing a website where the main section has a series of divs with looping background images, and I am utilizing jQuery to animate their movement in order to create an illusion of an "ocean" of images flowing across the screen. let pos ...

What is the process by which Single Page Applications manage the Not Modified 304 response?

Imagine a scenario where a Single Page Application (SPA) built using angular or vuejs loads 3 components on a page, with each component making requests to different backend APIs. Now, if a user decides to refresh the page, those same 3 API calls are trigg ...

The JQuery Twitter client is experiencing issues in Firefox and is currently not functioning properly

I have created a small script to retrieve my most recent tweets using JQuery's $.getJSON() method. Interestingly, this script functions perfectly in Chrome and Safari, but it fails to display anything in Firefox! Take a look at the code snippet belo ...

The error message "Access-Control-Allow-Origin does not allow Chrome extension xhr cross-domain requests" is displayed

I'm having trouble making a request to the following URL: "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=dogs" from my popup.html. When trying to access it, I encounter this error message: XMLHttpRequest cannot load https://ajax.g ...

Express 4 does not support Angular ngRoute

I am trying to set up client-side routes using Angular along with Express 4. I have successfully used the ngView directive as per the guide ngView without Express, but once I enable Express routing, ngRoute stops working. How can I configure Express to wor ...

Creating a clickable link in the Bootstrap navigation bar using JavaScript

I would like to create a navigation bar with links that will dynamically change the webpage content when clicked using JavaScript. Here is an example of what I currently have: My Navigation Bar // Current JavaScript Method (Not Working) document.getEleme ...

What is the best way to choose the checked items and calculate the total price by adding up all the prices of the selected items?

Seeking help with utilizing JavaScript to identify and collect all checked items from an HTML file. I'm looking to determine which items have been selected from a menu, each of which has an associated price. How can I access the prices of the chec ...

Configuring multiple Restangular services with unique runtime settings

I'm currently working on a single page application using AngularJS (v1.6) along with Restangular (v1.6.1), but I'm facing some challenges with getting two separate Restangular services to function as intended. The main objective is to fetch a li ...

The JQuery .ajax call fails to make a connection with the server

I have a JQuery ajax request set up like this: <pre> var data = createXMLdata(); $.ajax({ url: '<a href="http://localhost:8080/foo/bar" rel="nofollow noreferrer">http://localhost:8080/foo/bar</a>', type: "PUT", data: ...

Invoke a JavaScript function from a dynamically inserted nested function

My primary application loads JavaScript files based on the page being visited: var MainApp = (function() { function loadPage(folder, template) { $.getScript('scripts/' + template + '.js') .done(function() { ...