performing cascading ajax requests

Currently, I am in the process of creating a replica of Hacker News using vanilla JavaScript.

In my JavaScript code snippet:

var apiResult = document.getElementById("apiResult");

function apiContent() {
    var url_end = ' https://hacker-news.firebaseio.com/v0/topstories.json? 
        print=pretty';
    var apiCall = new XMLHttpRequest();
    var links = [];

    apiCall.onload = function() {
        if(this.status == 200) {
            var apiData = JSON.parse(apiCall.responseText);

            for( var i = 0; i < apiData.length; i++){

                var url = 'https://hacker-news.firebaseio.com/v0/item/' ;
                var c_url = apiData[i] + '.json?print=pretty';
                var final_url = url + c_url;
                links.push(final_url);
            }

            for(var j = 0; j < links.length; j++) {
                var a = links[j];
                var secondRequest = new XMLHttpRequest();
                secondRequest.onload =  function() {
                    var secondData = JSON.parse(secondRequest.responseText);
                    console.log(secondData);
                }
                secondRequest.open('GET', a, true);
                secondRequest.send();
            }       
        }
        else {
            console.log('Unable to fetch data');
        }
    }
    apiCall.open("GET", url_end, true);
    apiCall.send();


}

The first API call 'url_end' provides the ID of the top 500 stories, returning only the ID. To retrieve the content related to each story ID, I'm making a second AJAX call with an updated URL containing the ID. However, this approach is not functioning as expected.

What adjustments should I make to ensure its proper functionality?

Answer №1

I have implemented a sample example wherein a closure is used to make multiple ajax calls inside a for loop. The sample JSON data can be accessed from . For detailed documentation, refer to .

FUNCTIONING JS CODE:

var apiResult = document.getElementById("apiResult");
function apiContent() {
var url_end = 'https://api.jsonstore.online/api/PsrWFAEwRVWXXU9y/cities';
var apiCall = new XMLHttpRequest();
var links = [];
apiCall.onload = function() {
    if(this.status == 200) {
        var apiData = JSON.parse(apiCall.responseText);
        for( var i = 0; i < apiData.length; i++){
            var final_url = 'https://api.jsonstore.online/api/PsrWFAEwRVWXXU9y/cities?id='+apiData[i].id ;
            links.push(final_url);
        }
        console.log(links); // Print Link Array
        
        for(var j = 0; j < links.length; j++) {
        (function(a){
              let secondRequest = new XMLHttpRequest();
              secondRequest.onload =  function() {
                let secondData = JSON.parse(secondRequest.responseText);
                console.log(secondData);
              }
              secondRequest.open('GET', a, true);
              secondRequest.send();
           })(links[j]);
        } 
        
    }
    else {
        console.log('Unable to fetch data');
    }
}
apiCall.open("GET", url_end, true);
apiCall.send();
}
apiContent();

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

Storing the values of three checkboxes in individual variables to be passed into distinct columns

Below is the HTML code for checkboxes, with a function that limits only three selections: <form class="interestSearchCriteria"> <input type="checkbox" name="walking" value="Walking"> Walking <input type="checkbox" name="running" value=" ...

Incorporating a feeder into a Json data structure within Gatling

My json file has the following structure, { "OrderRef": "Rand12345" "siteContactName": "ABC", "siteContactNumber": "12345678", "contactMobileNumber": "12345678", "estimatedDeliveryDate": "2016-03-08", "orderLines": [ { "productC ...

Exploring JSON data structures within a C# Controller

Forgive me in advance for any errors in my terminology. I've read so much about this topic that I feel overwhelmed. I have been successfully passing parameters through AJAX to an MVC controller action, which returns a SQL datatable in JSON format for ...

Transfer your focus to the following control by pressing the Enter key

I came across a project built on Angular 1.x that allows users to move focus to the next control by pressing the Enter key. 'use strict'; app.directive('setTabEnter', function () { var includeTags = ['INPUT', 'SELEC ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

What is preferable: defining JSON schema properties or utilizing oneOf conditions within an array of objects

I am looking to represent a variety of objects in a schema through an array called contents. This array can include any number of elements, but they must fall into one of two categories: one type represents text while the other type represents images. Up ...

differentiating between user click and jquery's .click() method

There are <a href=".. tags on a page with an inline onclick attribute. If a user clicks one without being logged in, they will be prompted to log in. After logging in and the page refreshes, jQuery will trigger .click() on the <a> element to redir ...

Searching for and modifying a specific subdocument in Mongoose

I am currently working with the schema for a document called Folder: var permissionSchema = new Schema({ role: { type: String }, create_folders: { type: Boolean }, create_contents: { type: Boolean } }); var folderSchema = new Schema({ nam ...

Event handler encountering outdated React props

We are currently working on a React-Redux web application that will feature multiple sets of Three JS scenes with synchronized zooming capabilities. To achieve this, we have decided to store camera data in the Redux store. Below is the code snippet for ou ...

Combining Arrays Equally and Alternating using JavaScript and Google Apps Script

I am attempting to evenly and alternately merge multiple arrays in JavaScript/Google Apps Script. I have about 5 or 6 arrays that I need to merge. I have tried two different methods, but unfortunately, neither has worked for me. I don't have much expe ...

What is the best way to empty the input field after a download event is completed in Node.JS?

For hours on end, I've been struggling with a persistent issue in my video downloader app. After successfully downloading a video, the input field where the URL is entered remains filled instead of clearing out. The screenshot below illustrates the p ...

Error 500 occurs when attempting a remote call to the internal server while exploring the Agile Web Development with Rails 4 book in Chapter

Currently in my 5th week of learning rails, I have been following the book "agile web dev with rails 4". After completing chapter 11, I decided to implement a remote call to remove all quantities of an item from the cart. However, I encountered an internal ...

Retrieve the URL of the webpage that initiated the AJAX request within the AJAX view

I want to access the /page/<some_id>/ from my request object in the view for /ajaxreq/, which is a different URL where my form data is being sent. Is there a way to achieve this? PS: I realize that this may be a design flaw and there are likely alte ...

Retrieving images from a server via AJAX requests

As I delve into learning AJAX, I encountered an issue with retrieving an image from my WAMPSERVER www.directory. Within the IMAGES file, there is an image titled logo.png that I'm attempting to access using the following code: function loadXMLDoc() { ...

Having difficulty retrieving model values from the angular ui modal dialog

Being only on my second day in the world of Angular, I am trying to navigate around Angular UI and build my first modal dialog. The modal dialog displays properly, but I'm encountering an issue with using models within it. You can view my demo on Plun ...

Converting an array to JSON in PHP: A step-by-step guide

Here's a PHP array that I'm working with: $var = explode("[;;]", $result['infoplantilla']); $numRow = count($var); $form = array ( "numRow", $numRow, "selectOption", $var, "prefijo", $result ...

Error message 'AVV_ERR_PLUGIN_NOT_VALID' encountered within fastify

I've encountered an issue while setting up the environmental variables in my fastify - react app. Can someone help me with resolving the 'AVV_ERR_PLUGIN_NOT_VALID' error that I'm receiving for the following fastify code? Your assistance ...

Is there a way to have one element automatically expand when another is selected?

I'm currently utilizing the date and time picker from . However, I need some assistance with the current setup. Currently, the date and time pickers are in separate input fields. In order to select a date, I have to click on the Date input field, and ...

Securing your API key while utilizing jQuery.getJSON: Best practices

I have a problem that I am trying to find a solution for... The issue is that I need to retrieve a JSON response from a server using .getjson, but the server necessitates the usage of an apikey which I am cautious about keeping secure and confidential. T ...

The Angular Factory service is accurately retrieving data, but unfortunately, it is not being displayed on the user interface

Here is a link to the complete source code angular .module('app') .factory('Friends', ['$http',function($http){ return { get: function(){ return $http.get('api/friends.json') .t ...