The controller is unable to provide the output in JSON format within the AJAX response

My task requires me to continuously call and fetch data from a REST API every second. To achieve this, I am calling the method with a time interval of 1 second as shown below:

var myVar = setInterval(function(){ getData1() }, 1000);

Below is the JavaScript function responsible for calling the controller:

function getData1(){
    var url=CONTEXT_ROOT+"/login/getdashboarddata1";
    $.ajax({ 
        type: "POST",  
        url: url, 
        contentType: "application/json",
        dataType: "json",
        data:{},
            success: function(data){
                alert(data);                    

            },
         error: function(e){
             //alert(e);
         }
        });
}

Here is my controller code:

@RequestMapping(value="/getdashboarddata1", method=RequestMethod.POST)
    public JSONObject @ResponseBody getDashboardData1() throws JsonParseException, JsonMappingException, NullPointerException{ 

        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/r_f22bc0ac1fe48bce/dataService/lastdata/";
        String user = restTemplate.getForObject(url, String.class);

        System.out.println("user: "+user);
        JSONObject obj = null;
        try {
            obj = new JSONObject(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return obj;
    }

When running the program, no alerts are displayed in the JSP. However, if I change the return type in the controller to String, it properly shows the JSON string response in AJAX.

For example,

[{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]

Despite doing this, I am still unable to retrieve data from the JSON string. Please help me identify the issue or suggest another way to accomplish this task.

Answer №1

If you have a JSON array

[{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]

You can access it using index:

data[0].sno

Answer №2

To retrieve data for the dashboard, make sure to return a String value from the function getDashboardData1()

After that, in the AJAX success callback, use the following code snippet:

JSON.parse(data)[0]['sno'];

If you encounter any issues or have suggestions for improvement, please feel free to share them.

Remember that you cannot access attributes of a string literal directly; it must be converted into a json object.

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

Is it possible to prevent the late method from running during the execution of Promise.race()?

The following code snippet serves as a simple example. function pause(duration) { return new Promise(function (resolve) { setTimeout(resolve, duration); }).then((e) => { console.log(`Pause for ${duration}ms.`); return dur ...

Using JavaScript to create CSS animations triggered on hover

Looking for a CSS Animation that will play forward once when the mouse enters a specific div, and then play in reverse when the mouse leaves. Check out my JsFiddle here. The div with the class ".item" should trigger the mouse enter event. The animation co ...

Exploring prototypal inheritance through Angularjs module.service设计(Note: This

Having worked with Angularjs for a few months now, I am curious about implementing efficient OOP within this framework. Currently, I am involved in a project where I need to create instances of a "terminal" class that includes constructor properties and v ...

Is it necessary to have the script tag as the first tag in the body of the HTML?

I have a script file that needs to be included by third party implementors on their web pages. It is crucial for this script to be the first tag within the body element, like so: <body> <script type="text/javascript" src="/my_script.js"></ ...

Encoding JSON and parsing data in case no results are retrieved

I am working on an AJAX project using PHP and JQuery, but I have encountered a problem. Specifically, I am facing an issue related to the dataType:"json" parameter in my Javascript code. Everything runs smoothly when the json_encode function returns rec ...

Data on global map routes displayed in highcharts react

After reviewing the react highmaps documentation, it appears that they have saved the map data in a hardcoded manner. Take a look at Link 1 Check out Link 2 In various tutorials, I noticed that the data is retrieved from high maps itself by passing a ke ...

Is the ASP AJAX control/extender failing to appear despite using the toolkitscriptmanager?

Struggling to incorporate a slider extender into one of the text boxes in my ASP web forms application using Visual Studio 2013. Despite multiple attempts and online tutorials recommending a switch from the original script manager to the AJAX toolkit scrip ...

Which tool would be better for starting a new Angular project: angular-seed or yeoman?

I'm having trouble deciding on the best approach to create a new AngularJS application. There seem to be various methods available, such as using angular-seed from https://github.com/angular/angular-seed or yeoman - http://www.sitepoint.com/kickstar ...

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

Weaknesses found in the React Js library bundled with create-react-app

Each time I initiate a new react project using npx create-react-app <AppName>, the following vulnerabilities are detected: 96 vulnerabilities found - Packages audited: 1682 Severity: 65 Moderate | 30 High | 1 Critical Node Version: v14.18.1 Npm: 7.20 ...

Ensuring Proper Sequence of Function Execution in Angular Directive

I'm a bit confused after reading the following two blogs: Blog I: Eric W Green - Toptal Order of execution Compile -> Controller -> PreLink -> PostLink Blog II: Jason More Order of execution Controller -> Compile -> PreLink ...

My requests are failing because jQuery AJAX does not send hashtag symbols

There's a challenge I'm facing while working with Elixir Phoenix and React.JS. The Token I have includes hashtags, and when I send a request to verify it, the hash symbols and everything after them are not being sent, causing the request to fail. ...

Tips for initiating and terminating the evaluation of a condition at regular intervals using JavaScript

I'm currently working on a JavaScript application where I need to achieve the following: Periodically check every 5 seconds to see if there is an element with the 'video' tag on the page. Once an element with the 'video' tag ...

Jquery Enhancement for Navigation

Recently, I have implemented a header and footer navigation on my website. The header navigation consists of 1 UL (unordered list), while the footer navigation comprises 5 ULs. My goal is to align the first child of each UL in the footer navigation with th ...

Leverage the Redux store as the source of data for sending a POST request

For my React project, I designed an input interface and saved the data in a Redux state. Afterward, I set up a new action for making an API call to post the data. When using a constant value as the "data" parameter, everything functions properly. However ...

Saving the current language (i18n) in local storage using VueJS

I'm working on a Vue app that utilizes Vue Routers and the Vue $i18n plugin. Here's how I've structured my HTML: <div class="locale-changer"> <select v-model="this.$i18n.locale" class="btn"> ...

By default, the text area element in Vue or Nuxt will send a message to the console

Every time I include a textarea html element in my Vue/cli or Nuxt projects, this message appears in the console. Is there a way to prevent this message from showing up in the console? <textarea rows="5" cols="33"> This is a textarea. < ...

Here is a unique rewrite:"Adjusting the prop of a Material UI Button component depending on screen size breakpoints can be achieved by utilizing

While using the Material UI Button component, I encountered an issue with conditionally determining the variant of the button based on screen size. Specifically, I want the variant to be 'outlined' on medium and larger screens, and no variant at ...

What is the best way to continue looping until my variable matches the user's input? JavaScript

As of now, this nested for loop continues until both i and j reach 3. How can I reset the variables once they have reached their maximum value so that the loop can continue running? Alternatively, is my current approach incorrect? for (i=1; i<=3; i=i+ ...

Sort the array by the elements in a separate array

Here is a filters array with three values: serviceCode1, serviceCode2, and serviceCode3. ['serviceCode1', 'serviceCode2', 'serviceCode3'] I have another array with approximately 78 records that I want to filter based on the a ...