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

Null Value Returned When Making an Ajax Post Request

I'm having trouble retrieving the id of the last inserted row after posting via ajax. When I var_dump the result, the function returns HTML instead of the id data. What am I missing here? Note: The save method should return the id of the last inserte ...

Enlarging the current division while reducing the size of the others when hovering

Currently, I am working on a school project that involves creating a slideshow on a webpage. However, I have reached a point where I am unsure of how to proceed. Here is the progress I have made so far: body { background-color: #252525; } #wrapper { ...

Combine the values of two numbers and then proceed to multiply them by another number with the help of

I am attempting to perform calculations on three numbers - adding two of them and then multiplying the result by the third number every time a key is pressed in one of the input fields. I am using PHP and Ajax to achieve this functionality. Below are snipp ...

Shuffling Numbers in an Array After Removing an Element with AngularJS

I am working with a JSON array that contains tasks: tasks = [{taskcode:1, taskName:'abc'}, {taskcode:2, taskName:'abc1'}, {taskcode:3, taskName:'abc2'}, ..... ]; If I delete a task with the nam ...

The height of a DIV element can vary based on

Looking at this div structure: DIV3 has a fixed height. The nested DIV5 will be receiving content from Ajax, causing its height to change. Additionally, there are some DHTML elements inside it that also affect the height. DIV5 has a fixed min-height set. ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

What is causing the array elements to be iterated through multiple times?

My goal is to display all the titles from an array called 'title element' containing 10 values. However, I am encountering a problem: The for loop outputs all 10 values repeatedly 10 times. The titles are: Title 1, Title 2, Title 3, Title 4, T ...

Utilizing nodejs to interact with a web service

Recently diving into Node.js and currently exploring how to utilize services with NodeJS. Seeking guidance on the NodeJS equivalent of the code snippet provided below: $.ajax({ type: "POST", url: "/WebServiceUtility.aspx/CustomOrderService", data: " ...

Creating a Cross Fade Animation effect with the combination of CSS and JavaScript

I've been attempting to create a similar animation using html and css. Below gif shows the desired outcome I am aiming for: https://i.sstatic.net/YsNGy.gif Although I have tried the following code, I have not been able to achieve the desired result ...

Unable to click on the icon when modifying Mui Text Field

Utilizing the MUI Text Field component, I have successfully added a select prop to transform it into a dropdown list with values and an icon. However, I encountered an issue while attempting to change the default dropdown icon to a custom one from Figma. D ...

"Effortlessly Populate Form Fields with a Dropdown Selection using Ajax - A Step-by

My HTML form has a dropdown for Available Clients. When I select an option from the dropdown, I want the form to auto-fill using Ajax: @using (Html.BeginForm("UpdateServiceClientInformation", "contracts", new { id = Model.Id }, FormMethod.Post, new { role ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

Display/Conceal WP Submenu

Struggling to switch the behavior of my Wordpress menu. Want it to display when clicked, not when hovered: <nav> <ul> <li> <?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ...

The Protractor actions().mouseMove function does not seem to function properly in Firefox and IE, although it works perfectly in Chrome

I've encountered an issue with the mouseMove command while using the actions class. The error occurs specifically when running the script on Firefox and IE, but works fine on Chrome. Below is the code snippet I attempted: browser.get("https://cherch ...

What is preventing me from using JavaScript to remove this class?

Struggling to implement a skeleton loading screen with CSS classes and JavaScript. The idea is to apply the 'skeleton' class to elements, style them accordingly, then remove the class using a timeout set in JavaScript. However, I'm encounter ...

What is the procedure for collapsing a table row or grid?

Looking at this image, I'm trying to find a way to collapse the breakfast row. Any ideas on how I can collapse either the entire tr or with a div? ...

Check out the selected values in Ionic 3

I am trying to retrieve all the checked values from a checkbox list in an Ionic3 app when clicked. Below is the code snippet: <ion-content padding> <ion-list> <ion-item *ngFor="let item of items; let i= index"> <ion-label>{{i ...

Unable to perform filtering on a nested array object within a computed property using Vue while displaying data in a table

Lately, I've been experimenting with different methods to filter data in my project. I've tried using various approaches like methods and watchers, but haven't quite achieved the desired outcome yet. Essentially, what I'm aiming for is ...

Having trouble retrieving the table value from an HTML document?

I am trying to retrieve specific information from this source: This information is crucial for fetching data from a database using a primary key. However, extracting this value has proven to be quite challenging. Upon document readiness, I execute the fol ...

Text box is not automatically filling up when selecting from dropdown menu

I am currently facing an issue with a dropdown box that offers three different selections. I want the Group ID associated with the selected group to automatically populate in the textbox below. How can I achieve this functionality? Whenever I make a selec ...