"Unspecified" following the execution of eval

Received this JSON object from backend services

[{"date":"2014-02-06","fontSize":14,"bgColor":"#000000","fontType":"Arial","userId":1012}]

Trying to extract and utilize the elements within the JSON object in my code, but encountering undefined when using eval function. For example: var date_time = data.date_time;
getting undefined for data.date_time
Tried various methods but still receiving undefined. Seeking assistance with a solution :) Beginner in javascript/json field, pardon the simplicity of the question ;) Code snippet below:

 var getUsersettings= "userId="+userId+"&sessionId="+sessionId; 
                     $.ajax({
                         type:"POST",
                         url: fetchUserSettings,
                         async: false,
                         cache: false,
                         dataType: "json",
                         data: getUsersettings,             
                         error : function(data) {
                             console.log("settings lost while fetching !!!!!");
                         },
                         success : function(data) {
                             console.log("settings fetched !!!!!");
                             if(data != undefined && data.length > 0){
                             console.log(data);
                        //   var obj = JSON.parse(data);
                             var obj = JSON.stringify(data);
                             console.log(obj);
                        //   obj = jQuery.parseJSON(obj);
                        /*   var data =eval('(' +data + ')');
                             console.log(data);
                            */  
                             data = eval('('+obj+')');
                             console.log("obj : "+data);
                             var date_time = data.date_time;
                             var font_size = data.fontSize;
                             var bg_Color = data.bgColor;
                             var font_type = data.fontType;
                             data.userId;
                            // console.log("---"+date_time+"-------"+font_size+"------"+bg_Color+"----"+font_type+"------"+data.userId);
                             }
                             else{
                                 console.log("no data abt fetching");
                             }

                         },
                         complete: function(xhr, textStatus) {
                             console.log("Status Code: " + xhr.status);
                         }
                     });

Answer №1

Hey there!

I'm a bit puzzled by your code and what you've done.

It seems like jQuery ajax is giving back JSON data that's already been parsed into a plain object.

One thing to note is that the first level of your plain object (JSON) is actually an array, so you'll need to access the first item in that array like this:

data[0]

After that, everything should be pretty straightforward.

Check out this example: http://jsfiddle.net/Valtos/4x44n/

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

JSON is reporting an issue with an object that has not been properly closed at a specific

This particular issue has been raised multiple times, however, I've yet to come across a solution for it... I'm attempting to retrieve the Facebook likes of a user and verify if they have liked my page. Here is the code snippet: public void ch ...

Is there a way to incorporate a fade-in effect when I trigger the expand function in this script?

I recently came across a jQuery plugin for expanding and collapsing content. I am interested in adding a fade-in effect to this plugin specifically when the EXPAND button is clicked. How can I accomplish this? $(document).ready(function () { var maxlines ...

CSS guidelines for layering shapes and divs

Currently, I am in the process of developing a screenshot application to enhance my understanding of HTML, CSS, and Electron. One of the key features I have implemented is a toggleable overlay consisting of a 0.25 opacity transparent box that covers the en ...

jQuery removes HTML tags from XML documents

I currently have a setup where a page is functioning as an AJAX loader with the help of jQuery. It is designed to retrieve XML documents, like the one shown below, and then place the values of title, authPhrase, and content into the appropriate div element ...

Verifying the activation status of a button within a Chrome extension

I have been working on a chrome plugin that continuously checks the status of a button to see if it is enabled. If it is, the plugin clicks on the button. I initially used an infinite for loop for this task, but realized that it was causing the browser to ...

What are the key indicators to differentiate between JavaScript and CSS code within a string?

I am faced with the challenge of receiving strings of code through simple POST requests. I am seeking a smart method to differentiate between JavaScript and CSS scripts without executing the script itself. My confidence level in distinguishing them accurat ...

npm command is not able to successfully update the JSON file

My attempt to create a custom NPM build command in my package.json file isn't going as planned. The command I'm trying to run before the actual build is this one: json -I -f ./src/environments/build.json -e 'this.patch++' Before incor ...

Is it possible to load asynchronous JS and then execute functions?

Is there a way to make my script behave like the Google Analytics JavaScript snippet? Here is an example of what I have: (function(d, t) { var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.src = 'myjs.js'; s.par ...

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

Double Triggering JQuery Event

I have a question regarding changing a property or attribute value and the execution of a change listener. Despite what I've read, in my case, it seems to trigger the listener. $(document).on('keyup change', '.fire', function( ...

What is the correct way to properly insert a display none attribute

I'm experiencing some alignment issues with the images in my slideshow. I used this example as a reference to create my slide: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_dots When clicking on the next image, it seems to mo ...

Having trouble making Json work with angular.js

I've encountered an issue while trying to retrieve forecast information from an external domain. Despite having both Angular and jQuery loaded, the HTML remains empty with no error messages reported by Chrome. var currentCityread = "Eindhoven ...

What's the best way to set up server-side pagination for mui-datatable?

Is server-side pagination for mui-datatable implementation a complex task? Challenges: I am facing difficulties in capturing the user-selected value from the rowsPerPage options. When a user selects '15', how can I update these values within ...

Preventing Flash of Unstyled Content in ElectronJS Browser Windows

Upon creating a new BrowserWindow and utilizing loadURL to incorporate an html file within the renderer, there is a brief instance where unstyled content is displayed for approximately half a second before the css is loaded. window.loadURL('file://&a ...

Is there a problem with my document.onload?

Currently, I am experimenting with a GreaseMonkey userscript and trying out something relatively straightforward; function test() { document.getElementById('elementhere').innerHTML = 'test'; } document.onload = test(); When I visit th ...

Ways to eliminate the initial digit of a decimal number if it is less than 1

I need assistance with modifying float values by removing the first number if it's lower than 1 In the "OPS" table section, I am calculating the sum of OBP and SLG obtained from a database. https://i.sstatic.net/cYwwW.jpg See the code snippet below ...

Create a feature that dynamically loads JSON Data onto a TableView in iOS as the user scrolls

I have developed an application that utilizes JSON data from web services. My web services consist of three pages, and when I add data to the tableview, it fills the first page. However, when I scroll the table view to the second page, the data from the fi ...

Having trouble with Angular ngRoute functionality?

I'm currently working on configuring a basic Angular app. Here is my main HTML: <html ng-app="CostumerApp"> <head> <title> Customers </title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstr ...

Utilizing Ajax in Rails 5: Trigger form submission upon clicking either of the two radio buttons via Ajax

Note: I have encountered similar questions before, but none of them match my specific scenario. Currently, I am creating a small Ajax form within my rails views using yes or no radio buttons. When I implement this form with remote: true, it functions corr ...

React, Storybook - Error TS2307: Button module not found or its type declarations. Can Storybook resolve this issue?

In my React project, I have a Button component created with "create-react-app" that uses absolute paths for importing. When trying to import { Button, ButtonProps } from 'Button', I encountered an error with TS2307. The absolute path 'Butto ...