Guide to creating several AJAX requests using a for loop

I'm currently experimenting with the Star Wars API (SWAPI) and attempting to display the names of all the planets. However, the planet information is spread across multiple pages. How can I go about making several AJAX requests in order to retrieve and display all of the data? Take a look at my code snippet below:

for (var i = 1; i <= 7; i++) {
    var xhr = new XMLHttpRequest();
    var link = 'https://swapi.co/api/planets/';
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var planets = JSON.parse(xhr.responseText);
            var responseHTML = '<p>';
            for (i in planets.results) {
                responseHTML += planets.results[i].name;
            }
            responseHTML += planets.results[1];
            responseHTML += '</p>';
            //console.log(planets.results.length);
        }
        document.querySelector('main').innerHTML = responseHTML;
    };
    xhr.open('GET', link);
    xhr.send();
    link += '?page=' + i;
}

Answer №1

Opting for a recursive function instead of a loop can ensure that each request is processed sequentially, waiting for the response before triggering the next one. This helps to maintain the order of results as expected, unlike with loops.

Additionally, utilizing fetch for making requests is recommended, as it represents a more modern approach to handling AJAX requests.

Below is an example of code implementing this concept:

// initialize index
let index = 0;

const performAjaxRequest = index => {
  // execute fetch request only if index is less than 7
  if (index < 7) {
    index++;

    // make fetch call with updated index in the URL
    fetch(`https://swapi.co/api/planets/?page=${index}`).then(res => {
       return res.json();
    }).then(res => {

       // display each country from the response on the screen
       for (var i = 0; i < res.results.length; i++) {
         document.body.append(res.results[i].name + ', ');
       }
       
       // recursion occurs here by calling the function again after receiving response
       performAjaxRequest(index);
    })
  }
}

// initiate the first call to the function
performAjaxRequest(index);

Answer №2

$('.checkbox:checkbox:checked').each(function (i, el) {
  $.ajax({
   // include your specific ajax code here
  });
});

The code above targets a group of checked checkboxes and sends data for each one that is checked.

Answer №3

The challenge presented here lies in the unpredictability of when the asynchronous requests will be completed, making it difficult to know when the process will finish. My approach to solving this issue is by using recursive functions, where each call of the function includes different parameters to make the next request.

If your goal is to store the responses of all these requests in a variable named "responseHTML," you can follow a structure similar to the one below:

var link = 'https://swapi.co/api/planets/';
var responseHTML = "";
makeRequest(1, 7, link);

function makeRequest(index, max, link) {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var planets = JSON.parse(xhr.responseText);
            responseHTML += '<p>';
            for (i in planets.results) {
                responseHTML += planets.results[i].name;
            }
            responseHTML += planets.results[1];
            responseHTML += '</p>';
        }

        if (index <= max) {
            link += '?page=' + i;
            index++;
            makeRequest(index++, max, link);
        } else {
            // All requests have been processed, so I display the responseHTML and terminate the code.
            document.querySelector('main').innerHTML = responseHTML;
        }
    };
    xhr.open('GET', link);
    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

Steps for implementing remote modals in Bootstrap 5 using CS HTML

I'm attempting to implement a remote modal window in Bootstrap 5 with C# MVC. The endpoint for the modal partial view is configured correctly. According to this discussion on Github, all that needs to be done is to call some JavaScript. However, it ...

Unable to retrieve the /socket.io/socket.io.js file in the client-side application

My server side application is currently hosted on heroku: The code snippet that is relevant to this issue is as follows: const express = require('express'), app = express(), server = require('http').createServer(app), ...

Utilizing GraphicsMagick with Node.js to Extract Page Frames from Multi-Page TIF Files

I am currently working with a JavaScript script that can successfully convert a single page TIF file to JPEG. However, I am facing difficulties in determining whether "GraphicsMagick For Node" (https://github.com/aheckmann/gm) has the capability to extra ...

Contrasting results when logging an element in Chrome versus IE

Running the script below in Internet Explorer gives the expected output for console.log(target_el): <div class="hidden"></div> However, when run in Chrome, the output changes to: <div class="visible"></div> To add a humorous twi ...

Tips for refreshing a specific div element at set intervals using JQuery AJAX?

I need to make updates to a specific div element without refreshing the entire HTML page. The code below currently works, but it reloads the entire HTML page. Additionally, I am working with different layouts where I have separate files for the header, l ...

Exploring the world of jQuery and Ajax: Experimenting with implementing a POST method through Ajax and retrieving the response in HTML

Hey guys, I'm currently attempting to set up a basic HTML post method using Ajax. Take a look at the code snippet below: <?PHP function fetchInstagramData($url) { $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => ...

What's preventing me from using the left click function on my published blog post?

This is my first time creating a blogger template and everything seems to be working correctly. However, I have encountered one problem. For some reason, I am unable to left click on my blog post. I have not installed any right/left click disabler and I&a ...

Error: The variable 'err' is not declared in this scope.at line app.post

Tools I am Using Windows 10 Firebase (Firestore) Postman JavaScript, Express I'm learning from this video(https://www.youtube.com/watch?v=-vo7cu0xP4I) Situation Description I attempted to make a post request using Postman for testing purposes, b ...

The replace function fails to recognize Cyrillic characters when combined with the /b flag

Struggling with a persistent issue, I've noticed that my code works perfectly with Latin characters but fails to recognize Cyrillic characters when using jQuery. $('p').each(function() { var $this = $(this); $this.html($this.text().re ...

javascript unable to delete cookie

After conducting extensive research across various articles and links on deleting cookies using JavaScript, I have encountered an issue where the JavaScript code does not seem to be functioning as expected. The code I utilized for setting cookie values usi ...

The select2 option seems to be malfunctioning as it is not

I have implemented a dropdown using Select2. Although I am able to retrieve data from the backend and display it successfully in Select2, I'm facing an issue with certain data that contains multiple spaces between words. For example: Test&nbsp;& ...

How can I display components using Angular CLI 5 without any visual output?

The index.html page is not displaying anything, not even the "App works" message that should appear in a basic initial project ng --version Angular CLI: 1.6.0 Node: 8.9.1 OS: darwin x64 Angular: 5.1.0 ... animations, common, compiler, compiler-cli, core, ...

What could be the reason for the inability to install Angular JS 2?

Setting up Angular 2 for experimentation on my VPS has been quite a challenge. The initial steps can be found here. Upon trying the first command: $ npm install -g tsd@^0.6.0 I encountered success. However, the second step led to an error: tsd install ...

html and css code to create a linebreak ↵

I received a JSON response from the server, and within this data is a "return line" in the text. {text: "I appear in the first line ↵ and I appear in the second line"} However, when I try to display this on an HTML page, the "return line" does not show ...

Retrieving information from Odoo using Ajax and displaying it in HTML

I am working in Odoo, creating a new project. import xmlrpclib username = 'admin' pwd = 'admin' dbname = 'odoo9' sock_common = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common') uid = sock_common.login( ...

Issue encountered when attempting to invoke a service from an Angular component within an office.js dialog

Our application utilizes Angular 5 and integrates Office.js to interact with Microsoft Office Word documents. Step 1: We use office displayDialogAsync to load the component. https://i.sstatic.net/uhT66.png Step 2: Inside the attribute-users component, an ...

What about a Comet solution using a PHP socket server?

Is it true that PHP doesn't handle scaling with a large number of users in a comet implementation? Is this limitation due to the Apache server or the PHP language? Can a socket server resolve this issue and improve performance? Seeking advice from s ...

Guide on incorporating the ":gt" filter from sizzle into vanilla javascript

I am currently working on adapting a jQuery plugin to be compatible with the AngularJS JQlite API, but I have encountered some challenges along the way. Here is an overview of the plugin: (function (e) { var $product = $('#product'), ...

Determine the total value derived from adding two option values together

I am attempting to calculate the sum of two select options and display the result. So far, my attempts have only resulted in returning the value 1. What I am aiming for is to add the values from n_adult and n_children, and then show the total under Numbe ...

Executing various axios requests to retrieve diverse data and populating multiple sections of the user interface in React Native

I am struggling to display various categories of movies on the same screen, such as "POPULAR MOVIES", "RECOMMENDED MOVIES", and "NEWEST MOVIES". I have been able to retrieve data for the "POPULAR MOVIES" section using an API call, but I'm unsure of th ...