Save the output of my Java function into a JavaScript variable

I have created a web application using JSP, CSS and HTML. The page contains six buttons, each of which calls a JavaScript method. For instance, the first button triggers the par() method.

<html>
<head>
<title>Welcome   d To Student University</title>
<link rel="stylesheet" type="text/css" href="../css/stlogin.css">
<link rel="stylesheet" type="text/css" href="../css/background.css">
<link rel="stylesheet" type="text/css" href="../css/back.css">
<script src="StInfo.jsp">
</script>

</head>
<body>
<div class=main>
    <div class=blank></div>
    <div class=welcome><h1 class=welcome><center>Welcome Student</center></h1>
    <div class=logout><a href='logout.jsp?value=st'>Logout</a></div></div>
</div>
<br>
<div class=menu>
    <div class=leftgap>.
    </div>
    <div class=option>
    <center>
    <button type="button" onclick=par() class="Bt_menu">Check Parsnal Info</button>
    </center>
    </div>
    <div class=option>
    <center>
    <button type="button" onclick=faculty() class="Bt_menu">All Faculty Details</button>
    </center>
    </div>
    <div class=option>
    <center>
    <button type="button" onclick=exam() class="Bt_menu">Next Exams Details</button>
    </center>
    </div>
    <div class=option>
    <center>
    <button type="button" onclick=atten() class="Bt_menu">Attendance Details</button>
    </center>
    </div>
    <div class=option>
    <center>
    <button type="button" onclick=Result() class="Bt_menu">Exam Result Details</button>
    </center>
    </div>
    <div class=option>
    <center>
    <button type="button" onclick=Notices() class="Bt_menu">College Notices / Details</button>
    </center>
    </div>
</div>
<p id=Table></p>
</body>
</html>

In this script tag is used as follows:

<script src="StInfo.jsp">
</script>

Now, let me show you my StInfo.jsp file where the Java script methods are located.

<%@page import="data.*;" %>
<%
ServletConfig con=getServletConfig();
ServletContext ctx=con.getServletContext();
DataRet d;
%>
function par()
{
try
{
// I set ctx.setAttribute("id") to 1 in the previous page, so here the output will be 1.
<%DataRet.setAtt(""+ctx.getAttribute("id"),"stlogin");%>
var id=<%=ctx.getAttribute("id")%>;               // When I do this, the value 1 is stored in 'id'.
var id=<%=DataRet.get(2)%>;                       // However, when I do this, nothing happens and the code doesn't work.
}catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}

document.getElementById("Table").innerHTML="<center><table border='10'><th>College Id</th> <th>Name</th><th>Father Name</th><th>Department</th><th>Year</th><th>Semester</th><th>Ph. No.</th><th>Address</th>\
<tr>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
<td>"+id+"</td>\
</tr></table><center>";


}

And here is my DataRet File:

package data;
import java.sql.*;
import connection.connection;
public class DataRet
{
static Connection c;
static ResultSet re;
static Statement s;
static String id;
static
{
try
{
c=connection.getConnect();
System.out.println(c);
s = c.createStatement();
System.out.println("Statement Object Created = "+s);
}catch(Exception e){System.out.println(e);}
}
public static void setAtt(String table)
{
try {
re=s.executeQuery("select * from "+table);
}catch(Exception e){}
}
public static void setAtt(String att,String table)
{
System.out.println("Table Started");
id=att;
int i=0;
try
{
re=s.executeQuery("select * from "+table);

while(re.next() && re.getString(3).equals(att))
{
i++;
break;
}
System.out.println("cursor on "+i);
}catch(Exception e){System.out.println(e);}
}
public static void change()
{
try{
re.next();
}catch(Exception e){}
}
public static String get(int val)
{
System.out.println("value obtained of "+val);
try{
String o=re.getString(val);
System.out.println(o);
return o;
}catch(Exception e){ System.out.println("Problem in Getting Value"+e);}
System.out.println("return null");
return null;
}
}

The issue arises when I call the method *<%=ctx.getAttribute("id")%> * in StInfo.jsp, it prints 1 in every column. However, when I try calling <%=DataRet.get(2)%>, the file fails to work properly...

Answer №1

When storing data from a JSP scriptlet, it should be a straightforward process similar to what you already have in place.

var id=<%=ctx.getAttribute("id")%>

However, it's important to exercise caution with the returned data. If the data is not guaranteed to be a number, it should be enclosed in quotes to prevent potential JavaScript errors. For instance:

If <%=DataRet.get(2)%> returns the string "TEST", the corresponding JS code should be:

var id="TEST";

Failing to do so could lead to issues as the variable TEST does not exist. It's also essential to remember to include semicolons at the end of each line and properly escape any characters that might disrupt the JS code. Remember, the JS code is yet to be executed post compilation of the JSP, treating it as if you manually wrote the JavaScript code yourself.

If the code isn't functioning correctly, start by verifying the output of <%=DataRet.get(2)%> and checking for any JavaScript errors.

I hope this information proves helpful.

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

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

Having troubles with angular due to doodle throwing errors?

https://codepen.io/tuckermassad/pen/rPYNLq I took the CSS doodle code from the above link and incorporated it into my angular component: <section class="main"> <css-doodle grid="5"> :doodle { @grid: 10 / 100%; } ...

Guidelines for incorporating JS in Framework7

I am developing an application using the framework7. I am facing a challenge where I need to execute some javascript in my page-content, but it is not running as expected. <div class="pages"> <div class="page close-panel" data-page="item"> ...

Passing data from a method callback to a function and returning a variable in the same function

Is there a way to properly return the latlon variable from the codeAddress function? The typical 'return latlon' doesn't seem to work, possibly due to scope issues. Any suggestions on how to resolve this? function codeAddress(addr) { ...

Utilizing Dojo DGrid to customize the appearance of data within cells

I am facing an issue with my dgrid where I want to style cells by underlining the text when the checkboxes are selected for the row. My initial approach was to add a CSS class to the item once the checkbox is checked for the row. However, this method did ...

Implementing a dynamic update of an HTML element's content with JSON data - Learn how!

My task involves creating a quiz application where I need to show the answers along with images of the choices stored in my JSON data. However, I encounter an error: Uncaught TypeError: Cannot set properties of null (setting 'src') when I attempt ...

What are some ways to create a responsive image design?

Currently, I am using the code below to enlarge an image when clicked on. I have attempted using media queries in CSS... I have also added another class in #modalPopupHtml# to adjust the size of the large image: .imgsize{ height: 600px; width: 800px; ...

How can HTML output be automatically indented?

Seeking a way to automatically indent the HTML generated by my PHP script. I currently use HTML Purifier for validating internal textbox inputs, but I have reservations about using HTML Tidy due to its lack of active development and numerous reported bugs ...

The switchView feature is currently malfunctioning and unable to access the content on the next page

For my application's admin panel design, I've divided my home into containers. The aim is to display details of clicked items in Images.html and Categories.html when a menu item in the 2nd container (also known as side bar) is clicked. However, m ...

Utilize PHP to sift through HTML content and extract a specific tag

How can I extract a specific form using PHP? $url = '<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <div class="waitmsg" id="WaitMessage ...

Tips for creating a webpage with a spotlight effect using the mouse cursor

My goal is to create a webpage that is completely dark (as in night without any light at all) and have the mouse cursor emit a light effect to illuminate the surroundings. What tools or techniques should I use to achieve this unique effect? I've searc ...

Is it possible to utilize the lighten css property within ngStyle in Angular?

Having some trouble with the lighten property in ngStyle and it's not working as expected. I have a color variable within my component that I want to utilize like so: <div [ngStyle]="{color: schedule.group.color, background: 'lighten(' ...

Display a list of errors from an array in JavaScript or jQuery, and output them into a designated <

I need assistance with displaying a list of error messages in a specific div. Within my code, I have a #error-list div and an array called errors that contains various error messages: var errors = ["First name is blank", "Last name is blank", "Company na ...

How can I use CSS to transform a "+" symbol to an "x"?

When I created an accordion using HTML, JS, and CSS, I encountered a problem. The "+" sign in the accordion does not rotate correctly as it should. Instead of rotating from the middle of the "+" sign, it rotates from the top. This is my HTML code: <di ...

The Angular promise refuses to resolve at my desired time

I am struggling with managing Angular promises in order to control when they resolve. In the code snippet below, my intention is to first retrieve KeyDataFromServer() and then proceed with executing the remaining commands only after all the keys have been ...

What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning. export default function initCarousel() { const carous ...

Eliminate Dates from the Past - Jquery Datepicker

Currently, I am developing a booking system for my client. I have successfully disabled Sundays and Mondays (the days she is not open). However, I am now working on enhancing the functionality by blocking out past dates. Although I have written a function ...

What is the best way to rearrange the elements in a database after they have been displayed?

I have a feature on my website where you can enter text into a textbox and then click a button to save it in a database. The saved entries are displayed along with buttons for deleting an entry and moving it to the top of the list. <?php $resultset2 = ...

Understanding the use of JSON and JavaScript is proving to be quite a challenge for me

Although I understand the "parse" and "stringify" methods for JSON, I am still struggling to use it effectively despite seeing many examples and questions. In a previous homework assignment, I created an image gallery with hard-coded links to images. Now, ...

Having trouble with clearing divs function not working as expected

I'm facing a challenge in properly aligning 3 div elements without resorting to adding padding at the bottom of the wrapping div, which isn't the most practical solution. Check out the issue demo here How would you suggest addressing this parti ...