The JSON output didn't render properly and returned as 'undefined'

I am dealing with JSON output from a web method, and I need to figure out how to render it properly. The data looks like this:

{"d":"[{\"id\":1,\"username\":\"deepak_nhm\",\"companyid\":4,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Deepak\",\"lastname\":\"Kerai\",\"avatarsmall\":\"/images_webdev/profile/634596544067649211654527189.jpeg\",\"company\":\"Orange\",\"CompanyRank\":1,\"OverAllRank\":3},{\"id\":2,\"username\":\"Mona_Co\",\"companyid\":1,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Mona\",\"lastname\":\"Sadhu\",\"avatarsmall\":\"/images_webdev/profile/AspNetForumAvatarguy35.jpg\",\"company\":\"3 Retail\",\"CompanyRank\":1,\"OverAllRank\":3}]"}

However, my attempts so far have only resulted in 'undefined' being returned. Here is the code snippet I am using:


<script type="text/javascript">
    $(document).ready(function () {
        GetProducts();
    });
    function GetProducts() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetContestants",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                // Replace the ul's content with the page method's return.
                var invoices = msg.hasOwnProperty("d") ? msg.d : msg;
                var invoicesInList = [];
                for (var i = 0; i < invoices.length; i++) {
                    invoicesInList.push("<li>" + invoices[i]["username"] + "</li>");
                    //console.log(msg.length);
                }
                $(invoicesInList.join("")).hide().appendTo("#ProductsList").fadeIn("slow");
            }
        });
    }
</script>

If anyone can provide assistance on how to successfully render the JSON output, I would greatly appreciate it.

Answer №1

To utilize msg.d as an object, you need to decode it since it is in JSON format. Here's an example:

var invoices = msg.hasOwnProperty("d") ? JSON.parse(msg.d) : msg;

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 a for loop to call a Node.js request function

I have arrays consisting of 8 elements each var array_pullrequest_id=["335","328","326","323","322","314","295","291"]; var array_uniqueName=["<a href="/cdn-cgi/l/email ...

If you click outside of a Div element, the Div element will close

I am looking for a way to implement a function that will hide a specific div when I click outside of its area. The div is initially set to Position: none and can be made visible using the following function: Div Element: <div id="TopBarBoxInfo1" oncli ...

Attempting to transfer a JSON file using jQuery-POST, but encountering an issue with the content

Attempting to send a JSON array with a POST request to a web server has been successful, except for the incorrect contentType of my object. An "each" loop iterates through my form, adding pairs of values to two items. Subsequently, these two items are app ...

Smooth scrolling to an anchor with jQuery

Having recently written a simple smooth scrolling function using the jQuery mousewheel extension, I found myself facing a challenge due to my lack of experience with $.mousewheel. The gist of my issue is that when the "south delta" is triggered, I invoke ...

Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more effic ...

Having trouble extracting values from this JSON array - need help parsing it

I am looking to extract the company names and their values from this JSON data. What is the best approach to achieve this? Below is a snippet of the JSON output: Array ( [version] => 2 [query] => web developer [location] => Hyderab ...

The Angular Factory service is accurately retrieving data, but unfortunately, it is not being displayed on the user interface

Here is a link to the complete source code angular .module('app') .factory('Friends', ['$http',function($http){ return { get: function(){ return $http.get('api/friends.json') .t ...

UI-Router causing issues with AngularJS anchorScroll functionality

Currently, I am utilizing ui-router and attempting to implement automatic scrolling within the controller. However, it seems that anchorScroll function is not working as expected. My assumption is that it may be due to having two '#' symbols in t ...

I strive to establish a strong link between React and Firebase

I am facing an issue with Firebase and React. The problem arises after clicking on my add-data button to insert data into the database. Below is the error message I receive in the console: Reference_impl.ts:482 Uncaught TypeError: db._checkNotDeleted ...

What causes the 'this' to be undefined in React event handlers?

It is common knowledge that in the React code provided, this will be undefined. Various approaches such as binding and arrow functions can solve this issue. What I am interested in is understanding the rationale behind this behavior. Kindly elucidate on ...

Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop. My array contains objects, with each object structured like this: arrofobj = [ {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":" ...

Creating a multipart/form-data request using JavaScript/jQuery

After much searching and experimentation, I have been trying to understand the process of constructing a request to be sent using something similar to $.ajax({ contentType: "multipart/form-data", type: "POST", data: ...

Having difficulty implementing Jquery UI effects within an HTML Dialog in Google Apps Script

Looking for a scrolling effect in an HTML Dialog with Google Apps Script. I've already tried this link and placed the code in the editor. However, when highlight buttons are clicked, they work but do not cause scrolling within the HTML dialog. < ...

Error: JSON parse error, unexpected '[' character at index 1367

My AngularJS front-end is connected to the backend using Restangular and a Java Servlet, which returns JSON data that is parsed to create a chart with Charts.js Angular Factory app.factory('graphService', function($http, Restangular) { ...

Tips for adding dropdown option values to an array

Here is a sample of my JSON data. I want to add the name as the key and the data as the value in a dropdown list option. { "id" : 1, "name" : "name1", "Year" : 2018, "data" : [ { "day" : 1.0, "count" : 34.0, ...

Detect the size changes of a React DOM node using hooks

Is it possible to measure a React DOM node during the window resize event? I followed the example provided in the React hooks-faq, but it seems to only work for the initial render. When I tried adding a useEffect to listen for the resize event, the callb ...

Encountering issues with extracting JSON data in ReactJS constructor using Jquery due to property of null error

Currently, I am delving into the world of ReactJS in order to create a web application that necessitates the use of Jquery for extracting remote JSON data from a server. The issue arises when attempting to extract this data remotely, as manually inputting ...

Using addClass and fadeIn simultaneously when hovering over an element

After writing JavaScript code that utilizes the JQuery library to swap classes on hover, I noticed that the transition between background images was quite abrupt. The code functions as intended, but I would prefer to incorporate a fadeIn and fadeOut effect ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

Next.js strips out query parameters

I've encountered an issue with my Next.js app. I have a page called my-page.jsx. Everything works fine when I navigate to /my-page?x=1&y=2 - the page is rendered correctly and the query parameters are read. However, the problem arises when the par ...