There was an unhandled type error stating that "undefiened" is not a function while processing a JSON

Hey there! I'm currently using JSON to send a list of songs to populate my table. The JSON response is working fine up until the controller URL. However, when I attempt to loop through it and display the details in my table, I encounter an error.


$(window).load(function(){
    $.get("/MusicPlayer/getSongList", function(data){
        var library = data;
        listSongs(library);
    });
}); 

function listSongs(library){
    var table = $("#table");
    var row;
    $("#table tbody").remove();
    library.forEach(function(song){ 
        row = $("<tr></tr>");
        $("<td />").addClass("song-select").append($("<input  
        />").attr({type:"checkbox",class:"checkbox",value:song.title})).appendTo(row);
        $("<td>"+song.title+"</td>").appendTo(row);
        $("<td>"+song.album+"</td>").appendTo(row);
        $("<td>"+song.artist+"</td>").appendTo(row);
        $("<td>"+song.rating+"</td>").appendTo(row);
        $("<td>"+song.composer+"</td>").appendTo(row);
        $("<td>"+song.genre+"</td>").appendTo(row);
        row.click(viewFunction());
        row.appendTo(table);
    });
}

[
    {
        "title": "15 - Jacob's Theme.mp3",
        "album": "The Twilight Saga - Eclipse",
        "artist": "Howard Shore",
        "rating": "2",
        "composer": "carter ruwell",
        "genre": "Soundtrack"
    },
    {
        "title": "07_-_Vennante.mp3",
        "album": "Andala Rakshasi (2012)",
        "artist": "Ranjith",
        "rating": "0",
        "composer": "Rathan",
        "genre": "TeluguMusic"
    },
    {
        "title": "08. One Simple Idea.mp3",
        "album": "Inception (OST)",
        "artist": "Hans Zimmer",
        "rating": "0",
        "composer": "null",
        "genre": "?????????"
    }
]

Answer №1

It seems like utilizing $.parseJSON is necessary in this case, as the variable library should ideally be a JSON-formatted string rather than an array.

$.parseJSON(library).forEach(function(song){ .....

Answer №2

A response in the form of a JSON is essentially a string that follows a particular format, despite being just a string.

In order to utilize it as data in Javascript, you must first parse it using the function JSON.parse.

Answer №3

You won't find the forEach function defined for a JSON object.

Instead, you can use a for loop:

for(var song in library) {
   console.log(song, result[song]);
}

Alternatively, with jQuery's each:

$.each(library, function(key, value) {

});​

forEach is designed for simple arrays and requires an environment that supports ECMAScript5. Check out this discussion too: For-each over an array in JavaScript?

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

Having trouble resolving a setInterval problem with JavaScript?

Yesterday, I learned about the setInterval function which allows me to execute a task or function after a specific amount of time. While I have successfully implemented the interval in my code, it keeps adding new lines with the date each time. What I re ...

Transform the Angular function into a factory and take advantage of caching

My query differs from others with a similar title. I am attempting to transform a function into a factory in order to share data across controllers, but unlike my other factories, this one is not functioning as expected. I have successfully implemented ot ...

a single line within a compartment

I am encountering an issue with the code snippet below, which is responsible for generating the location of different records within a table: return ( <TableRow> <TableCell > // some code_1 < ...

JS: Submitting form data through POST method but fetching it with GET method?

When using PHP to retrieve data, the $_POST method cannot be used; only $_GET. Why is that? Could it be that I am not sending my form data correctly? I assumed that by using request.open("POST"), the form would be processed as a POST request rather than a ...

Tips for maintaining rounded bar corners in chartJs when filtering data

I created a JSFiddle with rounded chartJs bar corners: https://www.jsfiddle.net/gcb1dyou. The issue arises when the legend is clicked to filter data, causing the rounded corners to disappear as shown in the image below: https://i.sstatic.net/8NOMa.png Whe ...

Explore the power of accessing XML data using JavaScript

Currently, I am dealing with an XML file and attempting to extract data from it. The structure of the XML file is as follows: <doc> <str name="name">Rocky</str> <str name="Last_name">balboa</str> <str name="age ...

Looking for a specific item within a nested object in MongoDB to carry out an update

I have a JSON dataset containing information about individuals, including their children: { "name": ":John", "age": 35, "kids": [ { "name": "tom", "age": 5 }, { "name": "tina", "age": 3 } ] } My goal is to ...

What is the reason for not receiving a JSON object in the response from my personal node.js/express server?

-- Exploring a New Challenge -- I am currently working on creating an e-form signup for a client as part of our business marketing strategy service. The form design is complete and looks excellent. Now, I need to connect it to the existing API that our bu ...

JSONP cross-origin request issue

Is it possible to determine the response status when making a JSONP request? For example, can you tell if the request was successful with a 200 OK status, or if the resource was not found with a 404 error code? Alternatively, is there a method to attempt ...

Silent failure of product image upload in Java with Magento2 REST API leads to unexpected outcomes

Recently, I set up a Magento CE 2.1.2 online store. My main goal now is to utilize Java for uploading products to my store through the Magento REST API. After successfully configuring 2 leg OAuth using Apache-commons-httpclient and ensuring seamless produc ...

Click on a specific date on the calendar in the Javascript Django application to retrieve items based on

I'm currently working on a calendar application using JavaScript and Django. I am struggling to figure out how to display items based on the selected date when clicking on a day. Is there anyone who can suggest a solution? My assumption is that I may ...

Struggles encountered while configuring React

I'm in need of assistance with setting up React, even though I have both Node and npm installed. When I enter the following command: npx create-react-app new-test-react --use-npm I encounter the following error message: npm ERR! code ENOTFOUND npm E ...

Click on every link to reveal a hidden div

When I click on and select the first link in the mainPart, I want to automatically select the first subLink div in the secondPart while hiding the other subLink classes. This sequence should be maintained: when the second link is selected, the second sub ...

Guide to automatically refresh the source link every 5 seconds using a different .php link

Is there a way to automatically refresh the source link every 5 seconds in order to display an image from another page on index.php? On index.php <img id="img1" class="imgNews" src="https://example.com/car.jpg"> On other.php <span id="link1"&g ...

What is the best way to stop an embedded mp4 video from playing when a dynamically generated button is clicked?

After making modifications to the QuickQuiz code found at https://github.com/UrbanInstitute/quick-quiz, I have replaced the img with an embedded mp4 video that loads from a JSON file. Additionally, I switched from using the original SweetAlert library to S ...

Mastering Number Formatting in VueJS

While working with VueJS, I encountered difficulties in formatting numbers the way I wanted. After exploring options like the builtin currency filter and vue-numeric, I realized they required modifications to achieve the desired look. Furthermore, these so ...

Looking to expand the width of the sub menu to reach the full width of the

Is there a way to use CSS to make a sub-menu start from the left side of the screen instead of starting it below the parent item? nav { margin: 0 auto; text-align: center; } nav ul ul { display: none; } nav ul li:hover > ul { di ...

Refreshing JWT Authentication in Angular

I am currently following a tutorial on Egghead.io, which can be found here. However, I am adding a MongoDB to fetch my users which is causing me some issues. I have managed to get everything working except for the part where it mentions that the /me route ...

What steps can be taken to solve the JavaScript error provided below?

My objective is to create a new variable called theRightSide that points to the right side div. var theRightSide = document.getElementById("rightSide"); Once all the images are added to the leftSide div, I need to use cloneNode(true) to copy the left ...

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...