Executing two fetch requests in Django using JavaScript will show the outcome within a single div

I am completely new to Javascript, so please bear with me! I am having trouble with the structure of my code. Despite attempting various solutions involving async functions, I cannot seem to get the order right or understand where I am going wrong.

Currently, I am using a fetch request to retrieve data from an API on my local server, which works smoothly. The JSON format includes the names of cryptocurrencies paired with usernames.

Once I have styled and inserted the initial data into divs, I proceed to make another fetch request to an external API. This time, I aim to acquire more data and insert it into the previously created divs based on the data sourced from my API.

However, the issue arises when the data fetched from the external API ends up being displayed in a single div instead of distributing them individually as intended. I have tried different approaches like forEach loops, for loops, adjusting placements, and utilizing global variables, but nothing seems to resolve the problem entirely.

The specific data I am fetching is the LOGO for each CRYPTOCURRENCY. Sadly, both logos end up in the first div with the id = cryptologo rather than in their respective corresponding divs with the same id.

I would greatly appreciate any assistance. Thank you!

Here is the snippet of my code:

document.addEventListener('DOMContentLoaded', function() {


fetch('/allfollowedcryptos')
  .then(response => response.json())
  .then(data => {

  // Print result
  console.log(data);
  
  for (i in data){

  var container = document.getElementById('maincont');    

  var savedcrypto = document.createElement('div');
  savedcrypto.style.height = '200px';
  savedcrypto.style.width = '1200px';
  savedcrypto.style.marginTop = '20px';

  var nameandlogo = document.createElement('div');
  nameandlogo.style.height = '200px';
  nameandlogo.style.width = '250px';
  nameandlogo.style.backgroundColor = 'red';
  nameandlogo.style.display = 'inline-block';

  var name = document.createElement('div');
  name.style.height = '60px';
  name.style.width = '250px';
  name.style.backgroundColor = 'pink';
  name.style.overflow = "hidden";
  var nm = document.createElement('h1');
  nm.innerHTML = data[i].crypto;
  

  logo = document.createElement('div');
  logo.style.height = '140px';
  logo.style.width = '250px';
  logo.style.backgroundColor = 'purple';
  logo.style.overflow = "hidden";
  logo.setAttribute('id','cryptologo');
  

  var cryptochart = document.createElement('div');
  cryptochart.style.height = '200px';
  cryptochart.style.width = '350px';
  cryptochart.style.backgroundColor = 'white';
  cryptochart.style.display = 'inline-block';
  

  var marketdetails = document.createElement('div');
  marketdetails.style.height = '200px';
  marketdetails.style.width = '600px';
  marketdetails.style.backgroundColor = 'green';
  marketdetails.style.display = 'inline-block';
  marketdetails.style.overflow = "hidden";
  
  name.appendChild(nm);
  nameandlogo.appendChild(name);
  nameandlogo.appendChild(logo);
  savedcrypto.appendChild(nameandlogo);
  savedcrypto.appendChild(cryptochart);
  savedcrypto.appendChild(marketdetails);
  container.appendChild(savedcrypto);

  

  cryptoname = data[i].crypto
  console.log(cryptoname)



     
     let url100 = `https://api.coingecko.com/api/v3/coins/${cryptoname}`;
  
     fetch(url100)
     .then(function(resp) {
     return resp.json();
     })
     .then(function(data){

        console.log(data)
        
        imgcont = document.getElementById('cryptologo');
        var img = document.createElement('img');
        img.style.marginLeft = '70px';
        img.setAttribute('src', `${data.image.small}`) ;
        imgcont.appendChild(img);
     })  

     

  }

  

  });
});

This is a snapshot of the resulting output:

https://i.sstatic.net/8DyCP.png

As evident from the image, all logos appear in one logo div rather than in individual ones. My goal is to have each logo displayed in its corresponding div.

Answer №1

Here's an example of code that demonstrates fetching country details using countries names and flags, utilizing the async and await methods.

const container = document.getElementsByClassName('container')[0];

// This section is for fetching country codes
async function getCountryCode() {
    const data = await fetch('https://restcountries.eu/rest/v2/all');
    const countries = await data.json();
    return countries.map((country) => country.alpha3Code);
}

// Function to fetch country details based on country codes
async function fetchCountryDetails() {
    const countryCodes = await getCountryCode();
    countryCodes.forEach(async (code) => {
        const data = await fetch(`https://restcountries.eu/rest/v2/alpha/${code}`);
        const countryDetails = await data.json();

        // Create elements for displaying country name and flag
        const countryContainer = document.createElement('div');
        countryContainer.style.marginBottom = '10px';

        const nameContainer = document.createElement('div');
        nameContainer.style.background = 'green';
        nameContainer.style.margin = 0;

        const imgContainer = document.createElement('div');
        imgContainer.style.background = 'blue';
        imgContainer.style.margin = 0;

        const name = document.createElement('h3');
        name.style.margin = 0;
        const img = document.createElement('img');

        name.innerText = countryDetails.name;
        nameContainer.appendChild(name);
        img.setAttribute('src', countryDetails.flag);
        imgContainer.appendChild(img);
        countryContainer.append(nameContainer, imgContainer);
        container.appendChild(countryContainer);
    });
}

fetchCountryDetails();

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

Using @keyup/@input events on Vue data property causes issues with form inputs

I'm having an issue with attaching a character counter to an input element. After displaying it back to the user, the input stops allowing me to enter more characters into the input box. <template> <div> <label class="l ...

I'm encountering an issue where the this.props object is undefined even though I've passed actions to mapDispatchToProps. What could

Summary: The issue I'm facing is that in the LoginForm component, this.props is showing as undefined even though I have passed actions in mapDispatchToProps. I've debugged by setting breakpoints in the connect function and confirmed that the act ...

What could be the reason for the token being undefined on the client side?

I have built an ecommerce site using nextjs and mongoose, integrating a jwt token in a cookie for client-side authentication. However, when trying to retrieve the token from the cookie named OursiteJWT, I encountered issues with it being undefined: https: ...

Navigating custom tokens between different pages

My application utilizes a custom log-in system that generates an encrypted Token to signify a user's logged-in status. This Token is then passed to another page (Dash.aspx) via the QueryString parameter. On Dash.aspx, the Token from the QueryString i ...

Using AJAX to submit a PHP form without refreshing the page

Currently, I am facing an issue with my PHP and AJAX code for posting data without redirecting the page. Surprisingly, the script works perfectly on the login page but not on other pages. The main difference I observed is that the login page uses if (empty ...

Protecting the source code of your Node.js application is just as important

When it comes to the security of the node application, is the source code protected from being viewed by clients like PHP? I am currently working on a website using node.js and I want to ensure that my server files are not accessible to others. While I&apo ...

Transferring PHP array data to JavaScript using echo

I'm currently in the process of working on a project that requires extracting data from a database and converting it into a JavaScript array. This array will be used to dynamically update a graph. Below is the PHP code I have written to retrieve the ...

Animating HTML elements with JavaScript and CSS when hovering the mouse

Recently, I stumbled upon the SkyZone website and was impressed by the captivating JavaScript/CSS/HTML effects they used. I was inspired to include similar effects on my own website. (Visit the Home Page) One noteworthy feature on their website is the n ...

Creating an input field within a basic jQuery dialog box is not possible

Can anyone assist me in adding an input box to my dialog box? I am working with jquery-ui.js. Here is the code I currently have: $(document).on("click",".savebtn",function(). { var id = $(this).attr("id"); $.dialog({ ...

Strategies for dynamically altering Vue component props using JavaScript

for instance: <body> <div id="app"> <ro-weview id="wv" src="http://google.com"></ro-weview> </div> <script> (function () { Vue.component("ro-webview", { props: ["src"], template: ` <input type="t ...

Testing lettuce with django and selenium is not running on Windows

Currently, my lettuce test suite using Selenium performs perfectly on Linux. However, upon installing Django and all necessary components on Windows in order to test the suite on IE8 and IE9, I encountered an issue. When attempting to run the test on Wind ...

Is it possible to control the functionality of the back button?

Is there a way to customize the behavior of the back button in a browser? For instance, instead of navigating back to the previous page (A.aspx) when a user is on B.aspx, can we make it go to Home.aspx? Is it possible to achieve this using ASP, C#, JavaSc ...

What is the best way to terminate a file upload initiated by ajaxSubmit() in jQuery?

A snippet of code I currently have is: UploadWidget.prototype.setup_form_handling = function() { var _upload_widget = this; $('form#uploader') .unbind('trigger-submit-form') // Possibly a custom method by our company . ...

Retrieve all properties associated with the current instance in the Angular 2 controller

I am looking to assign class variables with values from session storage if they exist, otherwise the variable will retain its default value initialized in ngOnInit. private getTableSessionItems = () => { var tSession = JSON.parse(sessionStorage.g ...

What is the most effective way to create a live preview using AngularJS and CSS?

Is there a way to dynamically change the background color of the body based on the hexadecimal value entered in a textfield, without using jQuery? I want the change to happen live as the user types. The current code works but it doesn't feel right. I ...

Having trouble with the Aurelia JSPM install -y command not functioning properly on Windows

I am currently following the Aurelia tutorial at I am attempting to install Aurelia dependencies using Gulp and JSPM. I successfully ran "jspm install -y" without any issues. However, upon opening the browser console, I encountered the following error: ...

JavaScript's GET request fails to include form data in the URL

Express Router Module for Book Details Form Page <form class="container col-md-5 signupform bg-white my-4 py-3 formShadow" method="GET" action="/admin/addBook/add" , onsubmit="return validate()"& ...

Burger menu sidebar - Conceal on click outside

Is there a way to hide the left sidebar when a user clicks outside of it? Jsfiddle I attempted using the following code: $('.nav').click(function(event){ event.stopPropagation(); }); I also tried adding .stopPropagation(); to the body cli ...

Can someone guide me on incorporating bluebird promises with request-extensible?

I'm interested in utilizing the bluebird library to create a promise-based asynchronous web client. Currently, I have been using the request-promise package for this purpose. To get started, I simply include the following lines of code at the beginnin ...

Using the feColorMatrix SVG filter in CSS versus applying it in JavaScript yields varied outcomes

If we want to apply an SVG filter on a canvas element, there are different ways to achieve this. According to this resource, we can apply a SVG filter to the CanvasRenderingContext2D in javascript using the following code snippet: ctx.filter = "url(#b ...