The Controller is failing to pass JSON Data to the AJAX Call

When trying to access JSON data in the Controller, it is not being retrieved in the Success function and instead showing an error message "Failed to load resource: the server responded with a status of 406 (Not Acceptable)" or executing the Error function. Can anyone assist me with this issue?

AJAX Call

 <script type="text/javascript">
  google.charts.load("current", {packages:["corechart"]});
  google.charts.setOnLoadCallback(drawChart);
  alert("I am okay");
  function drawChart () {
        $.ajax({
            url: "index.html",
            type:'get',
            headers: { 
                'Accept': 'application/json', 
                'Content-Type': 'application/json' 
            },
            //dataType: "json",
            success: function (jsonData) {
                alert("Success..............");
                alert(jsonData.jData);
                var data = new google.visualization.DataTable();
                // assumes "word" is a string and "count" is a number
                data.addColumn('number', 'Year');
                data.addColumn('number', 'Sales');
                data.addColumn('number', 'Expenses');
                data.addColumn('number', 'Profit');
                alert("inside.....");
                alert(data);
                for (var i = 0; i < jsonData.length; i++) 
                {
                    data.addRow([jsonData[i].profit, jsonData[i].sales, jsonData[i].year, jsonData[i].expenses]);
                }
                alert(data);
                var options = {
                    title: 'Company Details',
                };
                var chart = new google.visualization.PieChart(document.getElementById('Chart_div'));
                chart.draw(data, options);
            },
        error: function(e)
        { 
            alert('Error: ' + e);
           }
        });
    }
</script>

Controller

@RequestMapping(value = "/index",method = RequestMethod.GET,headers = {"Content-type=application/json"})
@ResponseBody 
public JSONArray getshowempPage() throws SQLException, JSONException
{ 
    JSONArray jData=gservice.GraphData();
    System.out.println(jData.toString());
    //Here i am getting This result
        jData = [{"profit":"200","sales":"2000","year":"2014","expenses":"400"},{"profit":"250","sales":"1170","year":"2015","expenses":"460"}]
    return jData;
}

Any assistance would be greatly appreciated.

Answer №1

Feel free to experiment with the script provided below

<script type="text/javascript>
  google.charts.load("current", {packages:["corechart"]});
  google.charts.setOnLoadCallback(drawChart);
  alert("I'm feeling good");
  function drawChart () {
        $.ajax({
            url: 'index.html',
            type:'get',
            dataType: 'json',
            success: function (jsonData) {
                alert("Hooray, it worked!");
                alert(jsonData.jData);
                var data = new google.visualization.DataTable();
                // assuming "word" as a string and "count" as a number
                data.addColumn('number', 'Year');
                data.addColumn('number', 'Sales');
                data.addColumn('number', 'Expenses');
                data.addColumn('number', 'Profit');
                alert("within.....");
                alert(data);
                for (var i = 0; i < jsonData.length; i++) 
                {
                    data.addRow([jsonData[i].profit, jsonData[i].sales, jsonData[i].year, jsonData[i].expenses]);
                }
                alert(data);
                var options = {
                    title: 'Company Information',
                };
                var chart = new google.visualization.PieChart(document.getElementById('Chart_div'));
                chart.draw(data, options);
            },
        error: function(e)
        { 
            alert('Error occurred: ' + e);
           }
        });
    }
</script>

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

How can I access the marker's on-screen location in react-native-maps?

Looking to create a unique custom tooltip with a semi-transparent background that can overlay a map. The process involves drawing the MapView first, then upon pressing a marker on top of the MapView, an overlay with a background color of "#00000033" is dra ...

Creating a WordPress post popup using Ajax with SimpleModal and jQuery

I tried to follow the instructions provided in this tutorial but unfortunately, I couldn't get it to work. This is the process I followed: 1 / Including in the header <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ...

Developing a multi-graph by utilizing several JSON array datasets

Currently exploring D3 and experimenting with creating a multi-line graph without utilizing CSV, TSV, or similar data formats. The key focus is on iterating over an array of datasets (which are arrays of objects {data:blah, price:bleh}). I am trying to a ...

Deactivate alignment for core/columns block in the theme.json file for Wordpress

Is it possible to completely disable the align (wide and full) options as well as the anchor from columns core block in theme.json? Here is my current code snippet: { "version": 1, "settings": { "blocks": { ...

Is there a way for me to determine which specific dependency is triggering a warning due to utilizing another dependency?

After analyzing my browser console, I found the following warnings: index.js:126 [WDS] Warnings while compiling. warnings @ index.js:126 (anonymous) @ socket.js:47 sock.onmessage @ SockJSClient.js:67 EventTarget.dispatchEvent @ sockjs.js:170 ...

Encrypting unencoded or invalid characters within a JSON dataset

There are occasions when the JSON received from a backend includes unencoded or invalid characters. For instance, there may be an (unencoded) character with ASCII code 31, causing issues when attempting to use jsonDecode. The reasons for the broken JSON-en ...

What is the best way to prevent the chaining of promises and catches in JavaScript?

I am currently developing an API using node and express to create users. However, I find myself struggling with error handling due to the asynchronous nature of MongoDB functions, which makes me feel like I'm trapped in a "promise hell." I anticipate ...

Every time I try to read a file using JavaScript, I keep running into the error: "Uncaught TypeError: fs.readFile is not a function." It's really frustrating

const fileSystem = require('fs'); fileSystem.readFile('analogData.txt', 'utf8', (error, content) => { if (error){ console.log(error); } else console.log(content); }); I am attempting to retrieve data f ...

Scaling down the screen for a smaller display

Having trouble achieving a specific effect and could use some assistance. My goal is to create an action where, upon clicking on the nav element (for simplicity, I've set it to be triggered by clicking anywhere on the body), the following should occur ...

The iframe is being loaded in the center of the page rather than at the top

I am currently facing an issue with embedding wetransfer into a website using iframe. The problem is that when the page loads, it automatically scrolls past the header section of the site instead of loading the new page at the top. How can I prevent this ...

When trying to link a Redis microservice with NestJS, the application becomes unresponsive

I am attempting to create a basic hybrid app following the guidance provided by Nest's documentation, but I have run into an issue where the app becomes unresponsive without any errors being thrown. main.ts import { NestFactory } from '@nestjs/c ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

The required element was not discovered

Whenever I attempt to execute npm run serve, it reaches 98% completion and then halts, displaying the following error message: An issue occurred while compiling with a total of 1 error: ...

Disable the ng-change event

Is there a way to prevent the ng-change event from happening? I have a select box with an option that I don't want users to select. Instead, I want to display a warning message and then revert back to the previously selected option. To achieve this, ...

Transitioning from one CSS id to another during page loading

Wondering how to fade in one CSS id on page load and then smoothly transition to another after a few seconds? Here are the ids: #background { background: url("images/am_photography_bg.jpg") no-repeat center -25px fixed; background-size: 100%; ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...

Experiencing issues updating JSON object within try block on Android Studio

Currently, I am working on a college assignment that involves extracting timetable data from an API. The format of the data retrieved is as follows: "1474239600000" : { "courseCode" : "CASE4", "moduleCodes" : [ "CareersService" ], "moduleD ...

``When multiple elements are clicked, the second click will remove the class

I'm struggling with jQuery. Essentially, I want the first click on "div 1" to add a class to the others and display "lorem ipsum" text, and continue this pattern for the rest. However, if I click on the same div again, the class should be removed and ...