Tips for transferring variable values from Java to JavaScript

As a coding novice, I find myself in a situation where I need to pass variable values from a Java class to JavaScript and update them as the data points of a high chart.

https://i.sstatic.net/giH84.jpg

The goal is to update these values in the chart shown below using JavaScript.

https://i.sstatic.net/ahBE6.jpg

I am seeking assistance on how to code this particular scenario. Thank you for your help!

Answer №1

$.ajax({
  url: "YourServletPath",
  type: 'GET',
  success: function(response) {
    //Perform data mapping here and pass it to the series parameter of your highchart method.
  },
  error: function(error) {
    handleErrors(error, parameter);
  }
});

Answer №2

To store data in an array and send it to your JSP page from the controller class, you can use the following code:

request.setAttribute("mydata", mydataarray);

In your Electricity.jsp file, retrieve the parameters like this:

var jsvarlist=<%=request.getAttribute("mydata") %>;

Note: JavaScript does not require explicit data types.


In your JS file, pass the list to your function. As it is an array, you can access the data as follows:

jsvarlist[0] //get the first value, etc.

If you need to import a Java class in your JSP, use the following syntax:

<%@ page import ="yourpackage.yourclass" %>

Finally, import the JS file into your JSP and call the function that accepts the list:

<script type="text/javascript" src="yourfile.js"></script>
...call your function 

Answer №3

Consider using ajax to achieve this task.

 var series = this.series[0];
 $.get("YourServletName",function(data){
                        series.addPoint([data.x, data.y], true, true);
                    });
                 }, 1000);

The code snippet above contains the following elements: the var series = this.series[0]; represents your array, the $get method is responsible for fetching data from your servlet, and

series.addPoint([data.x, data.y], true, true);
is used to add each point to the series. Before implementing this in your servlet, ensure you have a structure like the one below:

JsonObjectBuilder j = Json.createObjectBuilder();
        //Add code to retrieve desired information and assign it to "y".

        j.add("x", System.currentTimeMillis());
        j.add("y", YourResult);
        out.println(j.build());

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

After mapping the elements of the array twice, generate a new array

Two differently formatted bits of data may be received, each requiring different character stripping methods. The variable names are temporary and will be changed once the function is operational. const cut = flatten.map(obj => { return obj.file. ...

What could be causing the issue of undefined component props in Vue Router?

Recently diving into the world of Vue, I've been eager to master the art of utilizing Vue router. Smooth sailing with normal routing, I decided to spice things up by experimenting with dynamic routing. To my surprise, everything ran smoothly until I a ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

What might be causing the issue in the build process of my next.js project?

**Why is my Node.js YAML file causing an error?** name: Node.js CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: matrix: node-ver ...

Instructions on how to extract a specific timestamp from a video and utilize it to initiate an event

Is there a way to trigger an event or animation at a specific time in a video or frame of the video? For instance, I want text to appear when a video reaches 30 seconds. I've experimented with currentTime, tried using loadeddata, and attempted to u ...

jQuery failing to trigger onClick event for a specific group of buttons

Javascript: <script> $(document).ready(function(){//Implementing AJAX functionality $(".acceptorbutton").on('click', function(){ var whichClicked = this.attr('name'); ...

Having issues retrieving a JSON array in PHP with the json_decode function

Can someone assist me with passing and returning an array to a PHP script? I have successfully tested the json_encode portion, but I am facing issues with the json_decode on the PHP side. Javascript scid_list = []; $('.filter_on').each ...

When working on a Vue project, the Navbar @click functionality seems to

Having trouble with my navbar search form <form action="" method="post" class="search"> <input type="text" name="" placeholder="поиск" class="input" v-model="alls ...

How to disable the ripple effect of a parent button in Material UI when clicking on a nested child button?

Attempting to nest one button within another (IconButton inside ListItem with the button prop) is proving challenging. The issue lies in the fact that the ripple animation of the ListItem is triggered even when clicking on the IconButton. Ideally, I would ...

Utilizing an argument in the mapStateToProps function

This component features a counter along with two buttons for incrementing and decrementing the count. class App extends Component { render() { return ( <div className="App"> <h1>{this.props.counter}</h1> <b ...

Controlling international shortcuts for numerous npm packages

Within my root folder, I have 3 npm projects organized in a more complex structure than the following example (using webpack, JS frameworks, etc.), but for simplicity sake, here is the layout: root ├── root_index.js ├── package.json ├── p ...

Designing a system that effectively handles subtract requests from clients on a server

When a server receives requests on '/subtract', it should accept two parameters, 'a' and 'b', and then return the difference between them as a plain text response. I have already set up the server and added the necessary requ ...

Scrolling horizontally using jQuery and CSS

I have been experimenting with creating a horizontal scrolling page that moves to the right when scrolling down and to the left when scrolling up. Here is the current code: HTML <div class="scroll-sections"> <section id=&quo ...

Is it possible to create a "text carousel" using HTML, CSS, and JavaScript?

Currently, I am in the process of building a 'text carousel' on my own, without seeking assistance. The progress so far can be viewed here (please stretch it out, as it is not responsive yet). Specifically, I am aiming to replicate the text carou ...

The functionality of selecting all items in v-select does not result in saving all of them

I'm currently working on integrating a select all button into the v-select component of Vuetify. The issue I am facing is that even though I can use the button to select all options, when I attempt to save, not all items are saved. However, if I manua ...

How to retrieve the context of a .js file using jQuery $.ajax without automatically executing upon receipt

Upon fetching a *.js file using $.ajax, the scripts are executed upon receipt! Is there a way to fetch and execute it only when desired? Moreover, is there a method to remove these scripts at will? ...

What kind of mischief can be wreaked by a malicious individual using JavaScript?

My mind has been consumed by thoughts about the safety of my projects, especially when it comes to password recovery. On the password recovery page, users must fill out a form with valid data and complete a recaptcha test for security. To enhance user ex ...

Container struggling to contain overflowing grid content items

While creating a grid in nextjs and CSS, I encountered an issue. Whenever I use the following code: display: grid; The items overflow beyond the container, even though I have set a maximum width. Instead of flowing over to the next row, the items just kee ...

Utilizing AngularJS to implement a Currency Filter on the output of a personalized filter

I'm currently working on a custom filter that transforms zero values into ' - ' for display purposes. The goal is to display currency formatting for non-zero values. However, I encountered an unexpected token error while trying to implement ...

Modify the highlighted text within the EditText

My app contains a button and an EditText. When the button is clicked, the text from EditText is stored in the database. I want to enhance this functionality by adding special characters like AselectedtextA to the selected text fragment in the EditText, wit ...