Struggling to display my JSON file in an HTML element with AJAX

Having some trouble here. I can successfully print my JSON file content to the console using console.log, but now I'm trying to display it on the page.

I want to display the 'Information' section from the JSON file using innerHTML like this:

https://i.sstatic.net/TFX6V.png

The second part should display the 'Websites' section as a list.

This is my current JavaScript code:

var xhr = new XMLHttpRequest();

xhr.onload = function() {
    if(xhr.status === 200) {
        console.log(xhr.responseText);

        var jsonStr = JSON.parse(xhr.responseText);
        document.getElementById("info").innerHTML += Student[0].Namn + ", ";
    }
};

xhr.open("GET", "student.json", true);
xhr.send(null);

I'm having trouble accessing and displaying the specific object I need.

This is my JSON data:

{
    "Student": [
        {
            "Information": 
                {
                    "Namn" : "Emil",
                    "Email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2979f9b9e82993e99999cbbb2999f939b9ecdc09d9c">[email protected]</a>",
                    "City" : "Linköping",
                    "Website" : "http://studenter.miun.se/~empa1600/"
                }

        },
        {
            "Websites": [
                {
                    "Sitename" : "komplett",
                    "SiteURL" : "https://www.komplett.se/",
                    "Description" : "Great site for tech purchases"
                },
                {
                    "Sitename": "Inet",
                    "SiteURL": "https://www.inet.se/",
                    "Description": "Competing site against Komplett"
                },
                {
                    "Sitename": "SF",
                    "SiteURL": "https://www.sf.se/",
                    "Description": "When you're going to the movies with your friend"
                },
                {
                    "Sitename": "Code Academy",
                    "SiteURL": "https://www.codecademy.com/",
                    "Description": "Learn how to code"
                },
                {
                    "Sitename": "Miun",
                    "SiteURL": "https://www.miun.se/",
                    "Description": "Where we learn everything"
                }
            ]
        }
    ]
}

I want the first section to be displayed

Another screenshot of my current website: https://gyazo.com/ef4b02c9474f443747df6fcdaf5537b6

I once managed to display using innerHTML but it just showed undefined, which I don't understand.

How can I display the 'Information' section like the first image and then list the websites in a <li> element?

Thanks!

Edit: How do I now display and style the 'Websites' array from the JSON data? And have them as clickable links?

This is what I've tried:

function printOut(){
        jsonStr.Student[1].Websites.forEach(w => {
            document.getElementById("sites").innerHTML += w.Sitename + "<br>";
        });

    }
    printOut();

Answer №1

Give this a try:

let xhttp = new XMLHttpRequest();

xhttp.onreadystatechange= function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
    console.log(xhttp.responseText);

    let data = JSON.parse(xhttp.responseText);




    document.getElementById("info").innerHTML += Student[0].Name + ", ";




}
};

xhttp.open("GET", "student-info.json", true);
xhttp.send(null);

Answer №2

Your code is missing the Student variable. The Student property is part of the object that is returned from the JSON.parse() method and is stored in the jsonStr variable.

Additionally, the Namn property is nested within the Information property, so you must include it in your code like this:

jsonStr.Student[0].Information.Namn
.

You can find more information on accessing nested objects, arrays, or JSON data by visiting this link.

To access the Website data, you will need to loop through the array using a similar method. Here is an example:

var sitesList = "<ul>";
jsonStr.Student[1].Websites.forEach(site => {
    sitesList += `<li><a href="${site.SiteURL}">${site.Description}</a></li>`;
});
sitesList += "</ul>";
document.getElementById("sites").innerHTML = sitesList;

Answer №3

After reviewing the code provided earlier, I believe that substituting onload with onreadystatechange and updating your if statement to

if(xhr.readyState == 4 && xhr.status == 200)
would effectively ensure that the ajax message is transmitted correctly.

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

AngularJS and the power of checkbox filtering

Is there a way to use AngularJS to filter out values from a list of food items stored in JSON based on two checkbox selections? Check out my demo on Plunker ...

Endless Loop of Http Redirects in Node.js with Express

I need assistance with the code below which is meant to redirect all http traffic to https. // Implement redirect logic to ensure usage of https in production, staging, and development environments app.use((req, res, next) => { // Do not redirect to h ...

Tips for creating a state change function using TypeScript

Imagine the temperature remains constant for 20 minutes, but at the 21st minute, it changes. The state change is determined by a programmable state change function. How can I create a function to calculate the difference in state change? if(data.i ...

Move the cursor within the text area upon clicking the button

When the "+header" button is clicked, I am looking to automatically position the insertion point inside the text area. Currently, after pressing the button, the text box displays information like address, date, time etc. but the cursor does not start insid ...

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

Transmitting extensions via AJAX

I am having trouble sending navigator plugins with AJAX as I am only getting one plugin in the result. The plugin list currently shows: Shockwave Flash. However, it should display like this: Shockwave Flash - Chrome Remote Desktop Viewer - Native Client.. ...

When dealing with back-end data in JavaScript, converting long types can result in a

When parsing data of the Object type in C#, utilizing JavaScript on the front end to parse the data can result in loss of precision. <!DOCTYPE html> <html> <head> <title>Example using BigNumber.js</title> <script s ...

Manipulating object attributes in three.js using WebGL

I'm currently working on animating a sphere with increasing radii. Below are the key parts of my code: function create_sphere(){ var sphereMaterial = new THREE.MeshLambertMaterial( { color: 0xCC0000 }); var radius=2,segments=50,rings=50; sph ...

Tips for making a slide-in animation that doesn't require adjusting the browser size

As I work on an animation where an img object and text slide in from outside the frame of the webpage upon page load, everything seems to be running smoothly. But there's one glaring issue: right at the start of the page load, the webpage resizes for ...

Utilizing Firebase Cloud Messaging for push notifications in Twilio Conversations

I am currently facing a challenge in setting up push notifications using Twilio Conversations and Firebase Cloud Messaging on a Next.js 12 app. The documentation assumes the use of Firebase 8 syntax, but I am working with Firebase 9 in this case. I have be ...

The ItemFileReadStore fetch function encounters issues when the response data contains nested objects

I'm currently utilizing the Dojo toolkit to fetch data from an external JSON source, which is essentially a web service, via an AJAX request. I am then using this data to create an ItemFileReadStore, after which I utilize its fetch method to print out ...

Expanding the capabilities of the Express Request Object using TypeScript

Looking to enhance the Request object of express with a new property To start, create a middleware that verifies the session and token containing the companyId import { verifyToken } from '../utils/jwt/jwt'; declare module 'express-serve-s ...

Attempting to design a versatile button in react js that has multiple functions. On the initial click, it saves data, changes the display to "view", and with a second click, it redirects to the saved page

Is it possible to create a dynamic button in React Js (MERN STACK) that changes its functionality from "Save" to "VIEW" after successfully posting data to MongoDB and receiving a 200 response status? I've tried different methods but haven't been ...

How to Retrieve URL Before Closing a jQuery Window Using window.open()?

Is it feasible to retrieve the URL of a window.open window after triggering a window.close event when the user clicks the close button? How can I obtain the last URL visited right before the window closes? ...

Converting JSON data into a C# List of objects

As a beginner in Json, I've been trying to implement it without success. In my C# project, I have a json string returned on a .aspx page. {"ContactsListResult":[{"Contact":"Fred Smith","ContactID":25},{"Contact":"Bill Wilson","ContactID":45}]} My ai ...

Trouble seeing span in ion-item in Ionic 2: How can I display plain text instead?

It seems like I may be overlooking something, as I am experiencing an issue with adding a span to an Ion Item, where the span is not being rendered, nor is the div. <ion-card> <ion-card-title> </ion-card-title> <div> < ...

Create a password variable while typing

Looking to avoid interference from browsers with autocomplete and password suggestions while maintaining the show/hide letters feature. The goal is to keep the password stored as a variable, regardless of whether the characters are shown or hidden. The is ...

Problem with Jsdom retrieving document

I am struggling to utilize jsdom for loading a local HTML file. Here is the code snippet: var config = { file: "filename", scripts: ["node_modules/jquery/dist/jquery.min.js"], done: function(err, window){ con ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

Working with SimpleXML Objects in PHP, using functions like json_encode and json_decode

One of the functions within my application performs multiple tasks, including: Using Snoopy to capture a web page Loading the result into DOMDocument Converting DOMDocument into a Simple XML Object Using XPath to isolate a specific section of the documen ...