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

A method for selecting the checkbox in a mat-row that corresponds to a certain text with Selenium

I want to select the checkbox within a nested mat-row: <mat-row _ngcontent-dac-c252="" role="row" class="mat-row cdk-row ng-star-inserted"> <mat-cell _ngcontent-dac-c252="" role="cell" class=&quo ...

What is the process for refreshing HTML elements that have been generated using information from a CSV document?

My elements are dynamically generated from a live CSV file that updates every 1 minute. I'm aiming to manage these elements in the following way: Remove items no longer present in the CSV file Add new items that have appeared in the CSV file Maintai ...

Using Laravel with Ajax can sometimes result in successful requests, while other times they may fail

I am facing some issues with my code as a junior programmer. Sometimes when I call data using Ajax in laravel 5.7, it is successful and the data is retrieved. However, upon refreshing, sometimes it is incomplete and logs show an error 500 in my PHP. Strang ...

Populate a dropdown menu using Javascript

[Code] $.ajax ({ 'method': 'GET', 'source': '/bpv-registratie/periods/show_period_list_by_year.html', 'charge': function () { }, 'finish': function (xmlHttp) { ...

Is React capable of storing and recognizing images within its system?

As a junior developer, I find this aspect confusing. Specifically, does reusing the same image on multiple routes in React result in the user downloading it more than once in the browser? I am striving to understand whether using the same image repeatedly ...

What could be causing my Spring Data JPA query to be significantly slower than using Node.JS with oracledb?

After putting together two basic projects to compare frameworks, I encountered slow query performance while using Spring Data JPA during my recent project at work. To analyze whether the issue stemmed from the database or the framework, I conducted a smal ...

Challenges when utilizing the command "npm install" within a programmatic context

I'm really excited about the potential of using "npm programmatically," but I've hit a roadblock. The function "npm.load" doesn't seem to be triggering for me. None of the console logs inside of my "npm.load" or "npm.commands.install" functi ...

Using axios to retrieve data and then sending it to a localhost server using express

I'm a beginner in javascript and currently experimenting with fetching data from an API and posting it to my own server (localhost). For fetching the data, I am using axios as shown below: async function getNCAA() { axios .get(`https://api.th ...

What sets 'babel-plugin-module-resolver' apart from 'tsconfig-paths'?

After coming across a SSR demo (React+typescript+Next.js) that utilizes two plugins, I found myself wondering why exactly it needs both of them. In my opinion, these two plugins seem to serve the same purpose. Can anyone provide insight as to why this is? ...

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

Template is not populating with data (Angular)

Currently, I am honing my Angular skills by working on a simple project. I have been seeking answers to my queries on Stack Overflow as they closely align with the issue I am facing. My challenge lies in displaying asynchronous data before it is initialize ...

What is the best method for adding a header to a dynamically created table using JavaScript?

After receiving JSON data in my JavaScript, I have successfully converted it into an HTML table. Everything seems to be working fine, but I'm wondering how I can add a header to my table? Below is the code snippet: <script> $(document ...

The HTML grid is causing an irritating excess space on the right side of my website

After brainstorming an idea, I decided to create this website for testing purposes. However, the grid layout seems to be causing an unwanted margin on the right side of the page that is not associated with any HTML tag, disrupting the zoom functionality. ...

Utilizing Jquery Validation to Remove a Class Upon Form Validation Success

In my current registration process, I have a multipart form where each subsequent form is displayed when the next button is pressed without fading effects. Initially, the button appears faded. Here's a simplified version of how I handle the first form ...

React hitting recursion limit due to excessive shouldComponentUpdate checks

I'm currently developing a real-time updating dashboard using React. The data for the dashboard components is fetched via an Ajax call and then passed to each component successfully. However, I encountered an issue with one specific component that re ...

The Material UI Popover is appearing outside the designated boundaries

In my app, I am using the code below to implement a react-dates picker controller inside a popover element. The functionality works well in most scenarios, but there is an issue when the button triggering the popover is located at the bottom of the screen, ...

Translate data from two "contact form 7" date fields into JavaScript/jQuery to display the date range between them

NEW UPDATE: I was able to get it working, but the code is a bit messy. If anyone can help me clean it up, I would greatly appreciate it. <div class="column one-fourth" id="date-start">[date* date-start date-format:dd/mm/yy min:today+1days placeholde ...

Show segments of video stream on page using node.js

I am currently exploring Node.js and trying to understand how streams work, so please bear with me if I seem a bit unclear. After reading some beginner notes on streams, I decided to test it out. In my project files, specifically in public/images/videos/S ...

Substitute the information in the table with new data

I am working with an HTML table that has 5 columns, one of which contains dates. I need to convert the date format only if the data is not empty. To achieve this, I am utilizing moment.js for date formatting. While the date format conversion works perfect ...

Utilizing Selenium Chrome driver to pinpoint a specific attribute associated with a label

Can anyone help me with targeting and clicking on the specific regOption bar to proceed with the test? I attempted to instruct the driver to use the following XPath directly. driver.findElement(By.xpath("//*[@id='regOptions']/div[2]/div[3]/p[1] ...