Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++)
{
    AjaxRequest99 = null;
    AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request

    if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) 
    {
        AjaxRequest99.open("GET", "ajax.php?id=99&AreaID=" +encodeURIComponent(AreaID)+ "&month=" 
                +encodeURIComponent(document.getElementById("cboMonths").value)+ "&TimeSlot=" +encodeURIComponent(y), true);

        AjaxRequest99.send(null);

        AjaxRequest99.onreadystatechange = function()
        {
            if(AjaxRequest99.readyState == 4) 
            {
                var innerHTMLdata = AjaxRequest99.responseText.toString();
                /* Fetch data from server and display. */ 
                document.getElementById("timeDiv"+y).innerHTML = innerHTMLdata;

            }/* end if */            
        }/* end function */            
    }/* end if */            

}/* end if */  

I am attempting to use ajax multiple times to populate data in a series of divs: precisely 24, starting with timeDiv0, timeDiv1, timeDiv2, timeDiv3...... timeDiv23. Each call corresponds to the TimeSlot value and respective div e.g. TimeSlot=0 goes into timeDiv0.

I realize that the ajax calls here are overriding each other but I'm unsure how to fix this issue without duplicating code blocks 24 times. Note, it works when executed singularly outside the for loop, but only fills one of the 24 divs.

The following code successfully loaded images in 24 divs:

for(var y=0 ; y<=23 ; y++)
    document.getElementById("img"+y).src="ajax.php?id=15&AreaID=" +encodeURIComponent(AreaID); 

I aim to achieve a similar outcome without unnecessary repetition of code. Any suggestions?

Update: I have resolved the issue. See below for the solution

for(var y=0 ; y<=9 ; y++)
{
    testFunc(y, AreaID); // invoking an external function within the loop
}

An external function:

function testFunc(y, AreaID)
{
        var AjaxRequest99 = null;
        AjaxRequest99 = getXmlHttpRequestObject();

        if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) 
        {
            AjaxRequest99.open("GET", "ajax.php?id=16&AreaID=" +encodeURIComponent(AreaID)+ "&month=" 
                    +encodeURIComponent(document.getElementById("cboMonths").value)+ "&TimeSlot=" +encodeURIComponent(y), true);

            AjaxRequest99.send(null);

            AjaxRequest99.onreadystatechange = function()
            {
                if(AjaxRequest99.readyState == 4) 
                {
                    var innerHTMLdata = AjaxRequest99.responseText.toString();
                    /* Retrieve data from the server and render. */ 
                    document.getElementById("timeDiv"+y).innerHTML = innerHTMLdata;

                }      
            }
        }    
}

Answer №1

Organize the block of code into a function:

for(let i=0 ; i<=23 ; i++)
{
  (function(i) {
    let ajaxRequest = getXmlHttpRequestObject();
    //rest of the code

  }(i));
} //end of for loop

Answer №2

One possible approach is:

for(var y=0 ; y<=23 ; y++)
{
    makeRequest(y);

}

function makeRequest(y){
    var AjaxRequest17 = null;
    AjaxRequest17 = getXmlHttpRequestObject(); // function to create the request

    if(AjaxRequest17.readyState == 4 || AjaxRequest17.readyState == 0) 
    {
        AjaxRequest17.open("GET", "ajax.php?q=17&SectionID=" +encodeURIComponent(SectionID)+ "&day=" 
                +encodeURIComponent(document.getElementById("cboDays").value)+ "&TimeSlot=" +encodeURIComponent(y), true);

        AjaxRequest17.send(null);

        AjaxRequest17.onreadystatechange = function()
        {
            if(AjaxRequest17.readyState == 4) 
            {
                var content = AjaxRequest17.responseText.toString();
                /* Process server response and update display accordingly. */ 
                document.getElementById("timeDiv"+y).innerHTML = content;

            }/* end if */            
        }/* end function */            
    }/* end if */            

}

Answer №3

I have revamped the entire code to achieve the desired functionality without utilizing asynchronous = false, thus preventing browser freezing:

function handleAjaxRequest(url, callback) {
    var request = null;
    if (window.XMLHttpRequest) request = new XMLHttpRequest();
    else if (window.ActiveXObject) // for IE
    {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP")
        } catch (e) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP")
            } catch (e) {}
        }
    } else {
        throw ("Ajax not supported!");
        return;
    }
    request.open('GET', url, true);
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            if (typeof (callback) == "function") callback(request);
        }
    };
    request.send(null);
    return request;
}

function fetchData() {
    var value = parseInt(arguments[0]);
    if (value > 23) {
        alert("All data loaded up to 24!");
    }
    
    var url = "ajax.php?id=16&AreaID=" + encodeURIComponent(AreaID) +
        "&month=" + encodeURIComponent(document.getElementById("cboMonths").value) +
        "&TimeSlot=" + encodeURIComponent(value);
        
    var customCallback = Function('request', 'document.getElementById("divTime' + value + '").innerHTML =' +
        ' request.responseText;' +
        'fetchData(' + value + ');');
        
    handleAjaxRequest(url, customCallback);
}

fetchData(0);

Answer №4

To improve the efficiency of your ajax calls, consider setting them to be synchronous by using the asenkron false parameter like this:

for(var y=0 ; y<=23 ; y++)
    {
        AjaxRequest17 = null;
        AjaxRequest17 = getXmlHttpRequestObject(); // method implementation for creating the request object

        if(AjaxRequest17.readyState == 4 || AjaxRequest17.readyState == 0) 
        {
            AjaxRequest17.open("GET", "ajax.php?id=17&AreaID=" +encodeURIComponent(AreaID)+ "&month=" 
                    +encodeURIComponent(document.getElementById("cboMonths").value)+ "&TimeSlot=" +encodeURIComponent(y), false);

            AjaxRequest17.send(null);

            AjaxRequest17.onreadystatechange = function()
            {
                if(AjaxRequest17.readyState == 4) 
                {
                    var responseText = AjaxRequest17.responseText.toString();
                    /* Process and display data received from the server. */ 
                    document.getElementById("divTime"+y).innerHTML = responseText;

                }/* end if */            
            }/* end function */            
        }/* end if */            

    }/* end for loop */  

Answer №5

Load content sequentially using ajax

Here is a basic ajax function that works on modern browsers like Chrome, Safari, IE10, Android, and iOS.

function ajax(url, callback){//url,function
 let xhr = new XMLHttpRequest;
 xhr.open('GET', url);
 xhr.onload = callback;
 xhr.send();
}

This code demonstrates how to load content sequentially:

let current = 0;
const total = 23;

function handleResponse(){
 document.getElementById("divTime"+current).innerHTML = this.response;
 current++;
 if(current < total){
  ajax('url.php?id=' + current, handleResponse)
 }
}

ajax('url.php?id=' + current, handleResponse);

This approach ensures previous ajax calls are not overwritten.


Having multiple ajax calls simultaneously is not recommended.

If you still need to make multiple ajax calls at the same time, create separate instances of XMLHttpRequest.

 let ajaxCalls = [];

 ajaxCalls[0] = new XMLHttpRequest;
 ajaxCalls[0].CUSTOMID = 0;
 ajaxCalls[0].open('GET', 'url.php?id=' + 0);
 ajaxCalls[0].onload = function(){console.log(this.CUSTOMID, this.response)};
 ajaxCalls[0].send();

Answer №6

When it comes down to it, the key factor is the asynchronous nature of Ajax calls. Every Ajax request must be kept alive until it either completes or fails.

In your original code, only one Ajax request context is used. The loop initiates the first request, but then immediately replaces its context with the second one long before the first request is processed. This results in a situation where when the server responds (a few milliseconds later), there is no handler left on the browser side to handle the response (except for the 24th one).

Your workaround involves creating different contexts and callbacks for each request by storing them in separate closures within your global function.

However, this approach leads to firing off a barrage of 24 Ajax requests simultaneously to the server, potentially causing unnecessary overhead or even crashes if your PHP script is not designed to execute concurrently for the same request. Additionally, synchronizing your code upon completion of these requests will prove to be challenging.

Here is the method I implement for my own applications:

// --------------------------------------------------------------------
// Ajax lite
// --------------------------------------------------------------------
function PageCache (target, void_contents)
{
    // implementation details here...
}
// rest of the code...

In your scenario, you can utilize it as follows:

Firstly, some cleanup steps:

// compute_id() function definition should go here...

var Ajax = new PageCache (
     'ajax.php?$',          
     'error loading data'); 

1) simultaneous requests (not recommended)

// for loop code block goes here...

2) sequential blocking requests (very bad, don't do it unless absolutely necessary)

// another for loop code block goes here...

3) sequential non-blocking requests

// final code snippet goes 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

What is the best way to choose all checkboxes identified by a two-dimensional array?

I need help with a question div setup that looks like this: <div class="Q"> <div id="Q1"><span>1. </span>Which of the following have the same meaning?</div> <div class="A"><input type="checkbox" id="Q1A1Correct" /& ...

A guide on utilizing URL parameters in Express.js to deliver images as static files

Looking to dynamically serve images from an "images" directory in my project based on user input, how can I achieve this? For instance, https://localhost:3000/images?fileName=burger This URL should display the corresponding image in the browser. If any ...

How can I alter the background color while performing a transformation in JS/CSS?

I'm currently working on achieving a flipboard effect for some divs, where one side is white and the other is black. Here's what I have so far: setInterval(function () { document.getElementById('test').classList.toggle('flipped& ...

Create a JavaScript code snippet that replaces the innerHTML of the function document.getElementById with

In my limited knowledge of JavaScript, I have come across an issue with the following code: function example() { document.getElementById("example").innerHTML = "<script>document.write(example)</script>"; } Unfortunately, this code doesn&ap ...

Problems arise when using AngularJS' .run function after navigating to a different page

I have encountered an issue with ngRoute while navigating between pages in my web application. The main login page is called index.html, and the routing is controlled by the main js file. However, I face a problem when trying to use a .run block on a speci ...

AngularJS's $http.get function has the ability to read text files, but it struggles with reading JSON

I'm new to angularjs and I am struggling to retrieve data from a json file using the $http.get method. It seems to work fine when I try to read a simple txt file, but not with the json file. I can't seem to pinpoint where the issue lies... Belo ...

Guide on converting JSON to CSV in React by utilizing the map function

When I convert JSON data to CSV by clicking a button, it currently stores the data in the CSV file separated by commas. However, I want each piece of data to be on its own line. How can I achieve this? For example: Minor,Minor What I Want: Each item on a ...

Embrace positive practices when working with nodejs

What is the best way to enhance the readability of my code by replacing the extensive use of if and else if statements when detecting different file extensions? Currently, I have over 30 else ifs in my actual code which makes it look cluttered. // Retrie ...

Updating a Rails form with a dynamically changing belongs_to select field

My Rails3 app has a Site model, connected to a Region model which belongs to a Country. Currently, the site form includes a select field for Region filled from the Region model. However, I want users to update this list dynamically. I attempted to create ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

Issue with content overlapping when hamburger icon is tapped on mobile device

When the hamburger menu is pressed on smaller screens, I want my navbar to cover the entire screen. To achieve this, I included the .push class in my code (see the jQuery and CSS) to trigger when the .navbar-toggle-icon is pushed. However, after implemen ...

Enter text into a field on a different webpage and verify if the output matches the expected result

Possible Duplicate: Exploring ways to bypass the same-origin policy I'm facing a scenario where I have a form on my website that requires validation of a number. The validation process involves checking this number against another website where e ...

Tips for creating JavaScript event handlers for Laravel forms

Looking to create a form for my Laravel application that includes text input boxes, radio buttons, and optional values. Here is the basic structure of the form: <html> <head> <title>Form Generation</title> <body> <form act ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

Challenges encountered when using setState to assign values

Just started using React and running into an issue with updating state when changes are made to a Textfield. I'm working with a functional component where the initial state is set using useState. I feel like I might be overlooking something simple... ...

Modifying the id attribute dynamically using jQuery during runtime

In my project, I have a submit button with the id of "submit" that is used to save new records. // Function to add a new customer record $("#submit").click(function() { var data = $.param($("#form").serializeArray()); ...

Model with no collection involved

Take a look at this Model and View setup. Why is the indicated line not functioning as expected? var app = app || {}; (function () { app.CurrentUserView = Backbone.View.extend({ el: $('.avatar-container'), template: ux.templ ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

Issue with navigation links on HTML website not functioning as expected

I would like the dropdown menu items to be clickable. For example: Menu item: Services Sub items: - branding } These already have working links - marketing } However, when I try to replace '#' with a link for Services, it d ...