What could be causing my server to not fully read my json file?

I created a function that sends a get request for fav.json and assigned the id="fav_button" button to execute this function. Additionally, I configured an express server. However, upon clicking the button, only the last item in the json file is displayed. The fetched json file consists of an array of objects.

Various troubleshooting steps have been attempted, including using .send instead of .json or .sendFile, debugging the json file (with no issues found), and even attempting to utilize jquery instead – all with no success.

// script.js
function get_fav(e) {
    if (!e) {
        e = window.event;}
    el = e.target || e.srcElement;
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        if (xhr.status === 200) {
            let list = JSON.parse(xhr.response);
            for (var i in list) {
                let hold = fav_tem;
                hold = hold.replace('%title', list[i].song);
                hold = hold.replace('%artist', list[i].artist);
                hold = hold.replace('%mood', list[i].mood);
                document.getElementById('faves_field').innerHTML = hold;}}};
    xhr.open('GET', 'fav.json', true);
    xhr.send();}
const fav_el = document.getElementById('fav_button');
if (fav_el.addEventListener) {
    fav_el.addEventListener('click', get_fav, false);}
else {fav_el.onclick = get_fav;}...


// app.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    res.send(fs.readFileSync('public/index.html'));
});

app.get('public/fav.json', function(req, res) {
    res.json(fs.readFileSync('public/fav.json'));
});...

...app.listen(3003, function() {
       console.log('Server started on port 3003...');
   });

The purpose of my script is to fetch fav.json and display each object part in the blue boxes as follows: (in bold) Song - artist. Mood: mood(s). My application should listen for the request for public/fav.json and then send it.

However, despite following the outlined process, clicking the designated button results in only displaying the final object from the json file in the blue box below. If you wish to explore the full project (bearing in mind my limited web development experience), feel free to visit https://github.com/YungLonk/Practice-Node-JS. What could be lacking or incorrect in my approach?

Answer №1

When iterating through the list and updating the HTML, you need to be cautious of only displaying the last item from the list due to how the code is structured.

        for (var i in list) {
            let hold = fav_tem;
            hold = hold.replace('%title', list[i].song);
            hold = hold.replace('%artist', list[i].artist);
            hold = hold.replace('%mood', list[i].mood);
            document.getElementById('faves_field').innerHTML = hold;
        };

To avoid this issue, consider moving the variable declaration and HTML property assignment outside of the loop.

    let hold = fav_tem;
    for (var i in list) {
        hold = hold.replace('%title', list[i].song);
        hold = hold.replace('%artist', list[i].artist);
        hold = hold.replace('%mood', list[i].mood);
    };

    document.getElementById('faves_field').innerHTML = hold;

EDIT:

After reviewing your project briefly, it appears that fav_tem only contains one item. Once replaced, it cannot be replaced again as the original text no longer exists.

In such a scenario, you may want to consider appending the items instead. Here's an example:

    let favitems = "";
    for (var i in list) {
        let hold = fav_tem;
        hold = hold.replace('%title', list[i].song);
        hold = hold.replace('%artist', list[i].artist);
        hold = hold.replace('%mood', list[i].mood); 
        favitems = favitems + "<br />" + hold;
    };

    document.getElementById('faves_field').innerHTML = favitems;

Give this approach a try and let me know if it meets your requirements.

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

Changing integer values to string in Swift for JsonString conversion

{ "value" : 1234, "value2" : 123456 } transform it into { "value" : "123456", "value2" : "123456" } I am currently utilizing the ObjectMapper class with the intention of parsing JSON to Mapper class. However, the response has been altered due to sp ...

The replication technique in Threejs

I am experiencing an issue while attempting to clone some Vector3 objects, as the copied clones are created with all zero values in x, y, and z. Here is an example: When I use this statement console.log(this.geometries[j].vertices[i].multiplyScalar(1)); ...

Issue with onClientClick not functioning properly when performing a jQuery function call

How can I make a jQuery form appear when an ASP.NET server-side button is clicked by the user? Currently, when I click on the button during runtime, the page reloads quickly without displaying the jQuery form. I am aiming to achieve a similar effect show ...

javascript strange behavior

I am facing an issue with my code that is attempting to display images based on their height. Strangely, the code seems to work fine when I test it with 2 images, but fails when trying with 3 or more. Check out the site: Upon clicking a menu button, the ...

Implementing a dynamic navbar in Vue.js using Firebase authentication

I've been diving into a Vue.js project that allows users to sign up and log in. I've incorporated Firebase Authentication for the login and sign up functionality. Successfully, I've implemented the feature where the navbar state changes: whe ...

Ways to halt the expressjs server

After deploying my express and nextjs based app on EC2, I encountered an issue where the server automatically starts Nginx and node with different process IDs after I attempt to stop it by killing the process. This is happening even without using tools lik ...

Having trouble accessing the scrollHeight property of null when using Selenium WebDriver

I am currently working on a function in my code that is responsible for scrolling the page. This particular function was inspired by code used to scrape Google Jobs, which can be found here. However, I encountered an error that reads "javascript error: Ca ...

Sending PHP form data to Google Chart via AJAX

After creating a PHP form drop-down list of table names in a database that captures the user's selection, I aim to use that selected table name to generate a Google chart. However, I'm encountering difficulties in passing the variable through AJA ...

Can you provide an explanation for what the line "const { Nuxt, Builder } = require('nuxt')" is doing in this

Currently, I am working on a Nuxt project where I will be utilizing the Express framework on the server side. Upon setting up the Nuxt project and choosing the express option, I came across a new file named server/index.js which includes a basic template f ...

Use the mouse scroll to navigate and scroll a vertical-rl div from right to left

Here I have created a vertical-rl environment; (function() { function scrollHorizontally(e) { e = window.event || e; var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); document.documentElement.scrollLeft -= (delta * 50); ...

Implementing ReactJS production build with HTTPS on Express server

After successfully deploying my React app to a production server using Express, I've encountered an issue when it comes to securing it with SSL certificates. Below is the code snippet that worked for deployment: const express = require('express& ...

Issue with error handling not being triggered when calling SAPUI5 function()

IBAN validation within a SAPUI5 Wizard is causing some issues for me. I am utilizing a functionImport on a V2 ODataModel (sap.ui.model.odata.v2.ODataModel) to perform this validation. Despite receiving a 202 status code, the request actually failed. Here ...

The iOS device is experiencing difficulty parsing the Weathermap API in full

While I have successfully retrieved data from the weather map api, I am facing challenges in parsing the data accurately. Currently, I can only parse a specific part of the JSON data. The JSON data looks like this: { base = "cmc stations"; clouds ...

What is the best way to add a dictionary to a JSON file without compromising the integrity of the JSON structure?

Before I explain my issue, I want to clarify that this is not a duplicated problem; it is unique. I am trying to add data to a dictionary within a JSON file using the code below. Please note that items like k['Process'] are sourced from another ...

JOLT Conversion: Merge and extract data fields from various JSON arrays into a unified output array

Here is an example of a JSON object: { "questionResponses": [ { "responses": [ { "responseId": "1", "response": "response 1" }, { ...

Locate the parent element that has the smallest amount of space taken up by its child elements

My goal is to determine which container, among several <divs>, each containing multiple child <divs> of varying sizes, has the smallest amount of space covered by the child elements. <div class="container" id="first"> ...

Transform a string into an array that is then passed as an argument to AjaxManager

I am facing an issue while trying to transmit an array from jQuery on an .aspx page to a method in the codebehind using Telerik AjaxManager. My difficulty lies in converting the string to a list or an array using C#. The string (generated after using Json. ...

Retrieve all string values from an Angular POST request using Express

Here is a simple code snippet that sends a POST request to a server using express: $http.post('/blah', { boolean: true, stringBoolean: 'true', number: 213, stringNubmer: '44444444', string: 'adssd&apo ...

Upon clicking, choose a specific todo ID

I'm currently in the process of developing a basic todo application, and I am receiving data through props from a GraphQL Server in the following format: id:"5b3447a7b9d0e02144538972" text:"biibbb" My current issue is that when I click on the checkb ...

Having trouble with PHP's JSON encoding functionality?

Take a look at my code for validating with angular and php. I need to check the validity of this form <form ng-submit="dk()"> <label for="">Name</label> <input type="text" name="name" ng-model="formData.name"> {{errorName}} &l ...