Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions:

I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance,

Client 1: First Name - James,

Address - 1234 Maple Street

Client 2: First Name - Jack,

Address - 4321 Lorem Ipsum Lane

My Query: How can I populate the following 12 articles in HTML using the JSON Data with a For Loop in my JavaScript and Ajax Request?

    <article>
        <img class="photo" height="100" width="100">
        <hgroup>
            <h1 class="name"></h1>
            <h2 class="email"></h2>
        </hgroup>
    </article>

    <!-- Repeat this article structure 11 more times -->

`const Employees = (function () { let displayStudent = document.querySelector('.photo'); let name = document.querySelector('.name'); let email = document.querySelector('.email'); let phone = document.querySelector('.phone'); let streetAddress = document.querySelector('.streetAddress'); let city = document.querySelector('.city'); let state = document.querySelector('.state'); let zip = document.querySelector('.zip'); const ajaxCall = function () { let hr = new XMLHttpRequest(); let url = 'https://api.myjson.com/bins/zfhmr'; hr.onreadystatechange = function () { if (hr.readyState === 4) { if (hr.status === 200) { let myObj = JSON.parse(hr.responseText); for(let i = 0; i < myObj.length; i++) { displayStudent.src = myObj.results[i].picture.large; name.innerHTML = myObj.results[i].name.first + " " + myObj.results[i].name.last; } } } else { console.log("ajax error: " + hr.response); } }; hr.open("GET", url, true); hr.send(); }; return { init: function () { ajaxCall(); } }; }()); Employees.init();`

I'm struggling to populate more than one article at a time with just one client's information. Any assistance would be highly appreciated!

Thank you

Answer №1

Upon examining your code example and comparing it to the JSON response, I noticed something peculiar.

This is what your JSON response looks like...

{
    "results": [...]
}

The for loop in your code appears as follows...

let myObj = JSON.parse(hr.responseText);
for(let i = 0; i < myObj.length; i++) {
    displayStudent.src = myObj.results[0].picture.large;
    name.innerHTML = myObj.results[0].name.first + " " + 
    myObj.results[0].name.last;
}
  • It seems that you are attempting to iterate through an object that does not have a .length property, indicating that myObj is not an array.

  • Furthermore, myObj.results[0] consistently retrieves the first result.


Possible Solution

In order to address this issue, you may want to dynamically insert HTML elements within your for loop.

<!-- Inside your HTML file -->
<div id="articleContainer"></div>

// Within your JavaScript ajax response (upon success)
if (hr.readyState === 4 && hr.status === 200) { // confirms completion of ajax request
    let container = document.querySelector('#articleContainer');
    let strArticles = "";

    let myObj = JSON.parse(hr.responseText);
    for(let i = 0; i < myObj.results.length; i++) {
        let resObj = myObj.results[i];

        strArticles += '<article>' +
                            '<img class="photo" src="' + resObj.picture.large + '" height="100" width="100">' +
                            '<hgroup>' +
                                '<h1 class="name">' + resObj.name.first + ' ' + name.last + '</h1>' +
                                '<h2 class="email">' + resObj.email + '</h2>' +
                            '</hgroup>' +
                        '</article>';
    }

    // Integrating the generated HTML string into the designated parent container element.
    container.innerHTML = strArticles;
}

I hope this resolves the issue for you :)

Answer №2

When working with variables in a for loop, it's important to ensure they are within the scope of the loop and avoid nesting if statements. If you need to populate HTML snippets with data, using a template can be more efficient than querying individual elements with selectors.

const Employees = (function() {
  let displayStudent = document.querySelector('.photo');
  let name = document.querySelector('.name');
  let email = document.querySelector('.email');
  let phone = document.querySelector('.phone');
  let streetAddress = document.querySelector('.streetAddress');
  let city = document.querySelector('.city');
  let state = document.querySelector('.state');
  let zip = document.querySelector('.zip');

  const ajaxCall = function() {
    let hr = new XMLHttpRequest();
    let url = 'https://api.myjson.com/bins/zfhmr'; //https://randomuser.me/api/
    
    hr.onreadystatechange = function() {
      if (hr.readyState === 4 && hr.status === 200) { 
        let myObj = JSON.parse(hr.responseText);
        for (let i = 0; i < myObj.length; i++) {
          displayStudent.src = myObj.results[0].picture.large;
          name.innerHTML = myObj.results[0].name.first + " " + myObj.results[0].name.last;
          
        }
      } else {
        console.log("ajax error: " + hr.response);
      }
    };

    hr.open("GET", url, true);
    hr.send();

    console.log(hr);


  };
  return {
    init: function() {
      ajaxCall();
    }
  };

})();

Employees.init();
<article>
  <img class="photo" height="100" width="100">
  <hgroup>
    <h1 class="name"></h1>
    <h2 class="email"></h2>
  </hgroup>
</article>

// Repeat this article snippet as needed

An example:

// Performing an AJAX call or fetch to retrieve data

var data = [{
  email: 'something'
}, {
  email: 'something2'
}, {
  email: 'blah'
}, {
  email: 'blah2'
}, {
  email: 'blah blah'
}, {
  email: ':o blah'
}]


data.forEach(item => {
  var div = document.createElement('div')
  div.innerHTML = `<div>some fancy box////   ${item.email}   \\\\\\some more facy box</div>`

  document.body.appendChild(div);
})

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

Is it possible to handle both ajax form submissions and browser post submissions in express.js?

On my website, I have implemented a contact form using express.js (4.0). I am contemplating how to manage the scenario where a user disables JavaScript. If the last part of my routing function looks like this: res.render('contact.jade', { tit ...

Why are my indents disappearing when I save in VS Code?

Just starting out with HTML and running into an issue where my indents keep disappearing whenever I save. Here's an example of what's happening. Before saving: After saving: I've experimented with different formatting tools and double-che ...

How to display logged-in user information on the homepage

Code for multiuser login $scope.users = [ {uname: 'fida', password: 'fida', age:26, department:"science"}, {uname: 'anu', password: 'anu', age:23,department:"maths"}, {uname: 'nida&apo ...

Discovering the specifics of an appointment within a shift event using FullCalendar

The title of the question may not accurately depict the scenario I am about to discuss. I'm currently working with FullCalendar and utilizing an open source library that allows me to add resources at the top. You can view the outcome of this on Js ...

Proper alignment of div elements using Bootstrap

I am attempting to align 2 div elements side by side using Bootstrap code: <div class='col-12'> <div class='row'> <div class='col-6'> </div> <div class='col-6&a ...

When working with Vue, setting the default value for props as a computed property is an

props: { rules: { type: Array, required: false, default: () => [ (file) => !file || file.size < 10000000 || this.getJsonDataByLocale.less_than_10mb_message, (file) ...

Using Vue to input an array

I'm struggling with how to handle this issue. The task involves taking input which should be a URL, and the user should be able to enter multiple URLs. For instance: <input type="text" v-model="fields.urls" class=&quo ...

Angular, JavaScript, and PHP are three powerful programming languages that

This file contains HTML code <ul class="list"> <li id="numword" data-score="{{item.score}}" class="" ng-repeat="item in words track by $index"> {{item.word}} {{item.score}} </li> </ul> Here is the visual representa ...

JavaScript and HTML are commonly used programming languages for developing

By utilizing JavaScript, I was able to generate a table dynamically based on user input. For example, if the user enters 3 and clicks "go", a table with 3 rows is created. Using the .keyup function allowed me to target a column successfully. However, an i ...

Navigate to all hyperlinks in browser without the use of jQuery - specifically for Firefox OS

I stumbled upon this interesting solution on a programming forum. I'm curious, how does this code work without relying on jquery? $('a[href^=http]').click(function(e){ e.preventDefault(); var activity = new MozActivity({ name: ...

What is the best way to switch back and forth between two div elements?

I've been attempting to switch between displaying div .cam1 and div .cam2, however, I can't seem to get it to work. Here's the code snippet in question: HTML: <div class="cam1"></div> <div class="cam2"></div> CS ...

Guidelines on creating actionable functions using JavaScript

Having trouble connecting the form to the database and looking for a solution. This is the HTML form that I've been working on, attempting both POST and GET methods. <form id="register" action="script/register.js" method="post"> <label for= ...

Tips for adjusting the size of nav-pills when collapsing with bootstrap 5

I'm attempting to utilize Bootstrap to create active classes that display a nav-pill/container around the active section of my webpage. It works well on larger screens, but on smaller screens with the hamburger menu active, the nav-pill stretches acro ...

Guidelines for aligning a form in the middle of the screen (positioned between the navigation bar and footer

Before asking this question, I made sure it's not a duplicate by researching previous similar issues with no success. I'm currently utilizing Bootstrap 4. You can view my app at (I'm unable to post the CSS and HTML of my React app due to S ...

Executing a prop function within the useEffect hook: a step-by-step guide

I am attempting to address this warning in a react component Line 19:8: React Hook useEffect has a missing dependency: 'handleChange'. Either include it or remove the dependency array react-hooks/exhaustive-deps This is the component: ...

What are the steps to set up mocha to automatically monitor source or project files?

Is there a way for Mocha to only watch my source/project files and not the test files? The test files and source/project files are located in separate directories. Any help or guidance would be greatly appreciated. Thank you! ...

React router updates the URL without affecting the actual display

I am facing an issue in my React project where the URL changes when clicking a link, but the view does not update. I have a separate route and links file, and I can't seem to figure out the problem. Here is my index.js: import React from 'react ...

Angular service provided by MetronicApp

I've been working on integrating Angular services with the Metronic App. This is how I defined my service: angular.module('MetronicApp').service('shaperService', ['$http', function ($http) { this.shapers = function(param ...

Is there a way to show a loading indicator while waiting for ajax to finish loading?

While waiting for my messages to finish loading, I'd like to display a loading spinner. The loading spinner is implemented in my Message.vue: import backend from '...' export default { mounted: function() { this.loadMessages(); }, ...

Adapting CSS according to input selection

Forgive me for asking what may seem like a simple question. I am currently using the CSS code below to modify the background color of a label when its associated checkbox is checked: #project input[id="button1"]:checked + label {background-color:red;} Is ...