Understanding Java and JavaScript variables within a JSP webpage

I am currently working on populating a pie chart from Google with data fetched from my database. Although I have successfully retrieved the desired results in my result set, I am facing challenges in converting my Java variables into JavaScript variables to make them compatible with the Google code. In my attempts, I encountered an error while using the following code: var zipie = <%= zip1 %>; The error message stated that

zip1 cannot be resolved to a variable
. Directly calling my Java variable in the JavaScript code did not yield the desired outcome.

<script type="text/javascript">
google.load('visualization', '1', {
    'packages' : [ 'corechart' ]
});
<%
try {
    PieChartDAO pDao = new PieChartDAO();
    String sql = PieChartSQLCreation.getTopZipCode();
    ResultSet zipr = pDao.getTopZip(sql);
    int[] zip = new int[5];
    String[] zips = new String[5];
    for(int i = 0; i < 5; i++) {
        zip[i] = zipr.getInt("num");
        zips[i] = zipr.getString("zip_code");
        zipr.next();
    }
    int zip1 = zip[0];
}
catch (Exception e) {
    e.printStackTrace();
}
%>

var zipie = <%= zip1 %>;
google.setOnLoadCallback(drawVisualization);

function drawVisualization() {
    visualization_data = new google.visualization.DataTable();
    visualization_data.addColumn('string', 'Zip Code');
    visualization_data.addColumn('number', 'Number of Students');
    visualization_data.addRow(['Work', zipie]);
    visualization_data.addRow(['Eat', 2]);
    visualization_data.addRow(['Commute', 2]);
    visualization_data.addRow(['Watch TV', 2]);
    visualization_data.addRow(['Sleep',7]);
    visualization = new google.visualization.PieChart(
            document.getElementById('piechart'));
    visualization.draw(visualization_data, {
            title : 'Zip Codes',
            height : 260
    });
}
</script>

Answer №1

zip1 is restricted to the try block. Make sure to declare it outside of the block for proper scope.

int zip1 = -1; // set a default value

try {
    // [...]
}

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

Updating the jQuery mobile webpage

I have set up a small demo with two pages - the Home page and the Team 1 page. By clicking on the navigation menu, you can navigate to the Team 1 page from the Home page. However, if you are already on the Team 1 page and click on the Team 1 button again ...

Delaying consecutive calls to query on mouse enter event in React

Currently, I have a React component from antd that utilizes the onMouseEnter prop to make an API query. The issue arises when users hover over the component multiple times in quick succession, which floods the network with unnecessary API calls. To prevent ...

Encountering an Error in Node.js When Defining Routes Using Variable Routes

Here is the code snippet from my App.js file- var routes = require('./routes'); app.get('/', routes.index); //var abt = require('./routes/about'); app.get('/about', routes.about); This is the code from my index.j ...

Trigger a click event in jQuery to activate a form through a hyperlink

I'm facing an issue where I want to implement a password-reset form based on a certain flag being triggered. Currently, my code is set up to prompt the user to change their password if the password_changed_flag is not present. Depending on the user&ap ...

Tips for modifying the hue of the hint attribute within vue.js?

`<v-text-field id="loginPasswordId" ref="password" v-model="password" class="login-input" dense :disabled="loading" :hint="hello world" :loading="loading" maxlength= ...

Retrieving specific information from the Model and returning it as a JSON response using annotations

I am interested in receiving a JSON response with additional annotations. Currently, my JSON response looks like: { "id": 1, "startDate": [ 1993, 12, 12 ], "endDate": [ 2018, 11, 22 ], "totalDistance": 255, "totalPrice": 211 } How ...

Navigating through embedded arrays using Jade

I am trying to display the data retrieved from the QPX API in my Jade view. The structure of the data is as follows: { kind: 'qpxExpress#tripsSearch', trips: { kind: 'qpxexpress#tripOptions', requestId: 'Oq ...

A guide on embedding the flag status within the image tag

I would like to determine the status of the image within the img tag using a flag called "imagestatus" in the provided code: echo '<a href="#" class="swap-menu"><img id="menu_image" src="images/collapsed.gif" hspace = "2"/>'.$B-> ...

Traversing a 2-dimensional array in a diagonal fashion

I am facing a challenge with iterating through a 2D array of characters. I already have the code set up for iterating, but I'm struggling with ... This is my 2D array: a,v,i,o,n,l t,o,t,o,l,l m,a,r,c,o,e s,a,g,r,c,i o,e,n,z,o,g s,t,r,a,r,u Currentl ...

Updating a dataview inside a Panel in extjs 3.4

I am facing an issue with my extjs Panel component that includes a dataview item. Initially, it works perfectly fine in displaying images from a store. However, upon reloading the imgStore with new image URLs (triggered by a user search for a different cit ...

Angular failing to update $scope variable within controller

I need to implement a directive that allows file uploading directly to the browser angular.module('angularPrototypeApp') .directive('upload', ['$parse', function ($parse) { return { restrict: 'A', scope: fal ...

Is there a need for pagination code to retrieve all links and execute a task?

Looking to create a selenium code using Java to conduct image font and size verification, however facing an issue with pagination. The default page setting is 50, but how can I perform the font and size check on each page? My current code only checks the f ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

Issue with Calendar Control not loading in Internet Explorer 9 when using ASP

I have been trying to incorporate a calendar control in my code that selects a date and returns it to a text field. It worked perfectly fine on browsers prior to IE 8, but I'm facing issues with IE 9. Can someone help me troubleshoot this problem and ...

What is the best way to remove top divs without causing the bottom divs to shift upwards?

I am faced with a scenario where I must remove the topmost divs in a document without altering the user's view. Essentially, I need to transition from: ---------start of document div1 div2 div3 ---------start of window div4 div5 ------- ...

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

Having trouble confirming the selected checkbox in Selenium Webdriver using Java

While running my test, I encountered an issue when verifying a selected checkbox. Below is the snippet of my code: if (CheckboxForFirstCitizenship.isSelected()) { System.out.println("Checkbox is selected"); } else { System.out.println( ...

Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider. This is my approach so far: var img = document.createElement('img'); // (imagine here all the other fields being defined ...

Retrieve and utilize the dynamically produced values from the application's app.js in a script that is accessed using

In my Express.js Node web app, I generate a string in app.js during initialization: // app.js var mongourl = /* generated based on process.env.VCAP_SERVICES constant */; There is a script that I import into app.js using require(): // app.js var db = req ...

The problem with utilizing the Node `util.inherits` method

I have encountered an issue with a 'this problem' in a Node server. It seems that replacing worker.stuff with worker.stuff.bind(worker) is necessary for it to function correctly. Is there a way to incorporate the bind method into the Worker Clas ...