Utilizing jQuery to extract JSON data from various URLs and insert it into multiple div elements

I have an HTML list containing 4 items, each with its own assigned id. My goal is to retrieve JSON data from multiple URLs using AJAX for each item in the list and then parse the data into the respective item's id.

Expected outcome: Each item receives the JSON data and displays the output within its corresponding div element.

Actual outcome: Only one of the items successfully displays the JSON data.

CODE:

$(window).bind("load", () => {

    const urls = ["http://35.187.8.168:88", "http://35.187.8.168:89"];
    const ids = ["#serv1_players", "#serv2_players", "#serv3_players", "#serv4_players"];
    $.ajax({
        url: urls.pop(),
        dataType: "text",
        success: function (data) {
            var json = $.parseJSON(data);
            $(ids.pop()).html(json.current_players + " players");
        }
    });

});
.worlds-panel {
background-color: rgba(3, 155, 229, .37);
width: 184px;
margin: 2px;
border-radius: 10px;
padding: 5px 15px
}
ul.worlds-dropdown .selected, ul.worlds-dropdown li:hover {
background-color: rgba(16, 246, 136, .47);
width: 164px;
color: #fff;
}

ul.worlds-dropdown {
padding: 0;
margin: 0 0 0 -5px;
list-style-type: none
}

ul.worlds-dropdown li {
padding: 8px 16px;
border-radius: 6px;
line-height: 1.429;
-webkit-transition: .25s;
transition: .25s
}

ul.worlds-dropdown img {
display: block;
position: absolute;
width: 24px;
height: 24px;
margin-top: 4px
}

.worlds-text {
margin-left: 35px;
margin-top: 2px;
color: #fff
}

.tag {
margin-left: 123px;
position: absolute;
margin-top: -28px;
border-radius: 4px;
font-size: .65rem;
padding: 2px 4px;
text-align: center;
color: #fff;
background-color: #0091ea;
font-family: Ubuntu
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="worlds-panel">
<ul class="worlds-dropdown">
    <li onclick="setserver('35.187.8.168:443');">
        <img src="resource/images/ffa.png">
        <div class="worlds-text">FFA</div>
        <div class="tag" id="serv1_players"></div>
    </li>
    <li onclick="setserver('35.187.8.168:444');" id="worldsDefault">
        <img src="resource/images/ffa.png">
        <div class="worlds-text">Instant</div>
        <div class="tag" id="serv2_players"></div>
    </li>
    <li onclick="setserver('35.187.8.168:445');">
        <img src="resource/images/ffa.png">
        <div class="worlds-text">Instant 2</div>
        <div class="tag" id="serv3_players"></div>
    </li>
    <li onclick="setserver('35.187.8.168:446');">
        <img src="resource/images/ffa.png">
        <div class="worlds-text">Minions</div>
        <div class="tag" id="serv4_players"></div>
    </li>
</ul>
</div>

Answer №1

Iterate over the list of URLs and perform an AJAX request to each one.

Here is a possible solution:

$(window).bind("load", () => {
    const urls = [
        { id: 0, url: "http://35.187.8.168:88", container: "#serv1_players" },
        { id: 1, url: "http://35.187.8.168:89", container: "#serv2_players" },
        { id: 2, url: "http://35.187.8.168:90", container: "#serv3_players" },
        { id: 3, url: "http://35.187.8.168:91", container: "#serv4_players" }
    ];

    $.each(urls, function (index, obj) {
        $.ajax({
            url: obj.url,
            dataType: "text",
            success: function(data) {
                var json = $.parseJSON(data);
                $(this.container).html(json.current_players + " players");
            }.bind(obj)
        });
     });
});

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

error encountered when trying to parse JSON due to an incorrect identifier

While putting together a dbt base model, I encountered an error message as shown below. It seems like there might be a small syntax error at line 6 that I am unable to identify. 15:40:22 Database Error in model base_datacenter_handling_unit (models/l10_st ...

Are there any CSS attribute configurations that I am overlooking?

Reviewing a colleague's CSS file, I stumbled upon an interesting section. They are a skilled CSS designer, so before jumping to conclusions, I wanted to make sure I am not missing something. In the code snippet below, it seems like they are unintenti ...

The alignment of the text seem to be malfunctioning

The text-align:center property isn't working as expected. Can someone please assist me in figuring out why it's not functioning correctly? Here is the HTML code snippet: <!DOCTYPE html> <html> <head> <title>Wheat and ...

Ways to modify the text of an HTML element when hovering over it

One of my elements contains the text &times; within a <span>. Is there a way to change this symbol to something else, like &infin;, when hovered over? <span class="change-text">&times;</span> When the mouse hovers over it, I ...

Is there a way to extract the timestamp in JavaScript from a string that includes the name of the timezone database?

Given the string: "2022/05/01 03:10:00", I am seeking to create a Date object with Chile's UTC offset. The challenge lies in the fact that due to Daylight saving time (DST), the offset changes twice annually. How can I obtain that Date obj ...

Using javascript to store HTML tags in a variable

Hey there, I have a quick question. Can someone help me figure out why this code isn't working? let plus = "+" + '<h1>'+"This is a heading"+'</h1>'; When I run the code, the output I get is: +<h1 ...

There was an error that occurred when attempting to read the property 'hasOne' of an undefined value: TypeError

Error Alert: Property 'hasOne' is undefined and cannot be read in Function.ADataMembers.associate. Check out ADataMember.js below: 'use strict' module.exports = (sequelize, DataTypes) => { var ADataMembers = sequelize.define(' ...

Difficulty in Verifying ECDSA Signatures Across React and Python Environments

Currently, I am tackling a project that requires me to create an ECDSA signature in a React application and then validate it in a Python backend. Although the signature generation and validation processes work perfectly within their respective environments ...

Issue with Django 1.11: Unable to display form validation errors in HTML page

After searching for ways to check if a form's name already exists in the database, I found this helpful link. It successfully prevents duplicate names from being entered, but I encountered an issue where no error message was displayed as expected. I&a ...

Pressing the button will trigger the creation or update of a JSON object

Hi there! I'm currently working on developing a CMS application and I need to create a JSON object to post to my API. However, I'm new to android development and could use some guidance on how to accomplish this task. Does anyone have any tips or ...

Adsense displays empty ad banners regardless of their predetermined size

Having trouble with Adsense banners? I have a page with three fixed-size banners (336 x 280) and sometimes they appear blank. It's random - one might work while the others don't, or none may work at all. The code is the same for each banner: < ...

Issue with Scrapy's ability to recognize the essential data field in a

Currently, I am attempting to extract information about biblical commentaries from a specific website. Below is the code that I have created for this purpose. The URL in start_urls points to the JSON file I am trying to scrape. I decided to use ['0&ap ...

Employing a combination of Mysql and Ajax to dynamically fill out a form based on the values entered

I am facing a challenge in populating a fairly extensive form with around 40 fields with data from a MySQL database. Generating the JSON array from the query is not an issue for me. echo json_encode($row); The objective I aim to accomplish seems to be u ...

Updating parent scope data from within a directive without relying on isolated scope bindings

What is the best method for passing data back to the parent scope in AngularJS without using isolated scopes? Imagine I have a directive called x, and I want to access its value named a. The desired syntax would be: <x a="some.obj.myA"></x> c ...

Inaccurate data saved to a cookie

I attempted to assign a string from PHP to a cookie and retrieve the value of that cookie using JavaScript. Take a look at my code snippet: <php $date=date('Y',time()); //assume it is 2017 setcookie("Year", $date, time() + 3600, "/"); ?> ...

using jquery to retrieve the current time and compare it

This is the code I currently have: var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() aler ...

What CSS selector should I apply to create a circular profile image for Buddypress users?

In my current WordPress project, I am utilizing the BuddyPress, WooCommerce, and WC Vendors plugins for enhanced functionality. To personalize each vendor's product listings, I decided to display their BuddyPress profile picture alongside their produ ...

Utilize Bootstrap 3 Datepicker version 4 to easily set the date using Moment.js or Date objects

I'm currently utilizing the Within my project, I have a datetime picker labeled as dtpFrom <div class='input-group date ' id='dtpFrom'> <input type='text' class="form-control" /> <span c ...

Implementing a horizontal scrollbar for an AJAX datatable

Is there a way to incorporate a horizontal scrollbar into an Ajax Datatable? I attempted to use "ScrollX" :true, however, this method did not prove successful. $(document).ready(function () { $('#myDataTable1').DataTable({ "aj ...

How can I implement an authentication process in JQuery Terminal using a JavaScript function instead of PHP?

I'm currently working on a project where I am using jQuery Terminal for a command line interface to execute functions. I have been attempting to utilize its built-in authentication feature, but I am interested in having it call a JavaScript function ...