Update the SQL database by transferring star ratings from a JSP file

Utilizing JSP to showcase information obtained from user queries, I have implemented a system where contextual data and the query itself are saved in a MySQL database using JDBC each time a new query is input. To enhance user interaction, I wanted to incorporate a rating system that allows users to rate each result by clicking on numbered stars (e.g., ** ***** **** corresponds to 2 5 4). Here is the code snippet from my JDBC:

PreparedStatement preps = null;

preps = dbMySqlConn.prepareStatement("" +
        " UPDATE " + dbName + "." + tableNameOutput +
        " SET" + " ratings = ?" +
        " WHERE id = " + queryID , Statement.RETURN_GENERATED_KEYS);

if (stars != null) {
    preps.setString(19, stars);
}

preps.execute();

The visual representation of the rating system in my main JSP file looks like this:

<form name="rating">
    <input class="star star-5" id="star" + sessionTime + i + "-5" type="radio" onClick="javascript:saveRating()" name="star"/>
           <label class="star star-5" for="star" + sessionTime + i + "-5" title="Perfect match"></label>
    </input>

    // Other star inputs go here

  </form>

This form triggers a JavaScript function when a star rating is clicked:

function saveRating(){

    if ($('.star.star-5')[0].checked){
        alert("Rating 5 saved");
    }

    // Additional checks for other star ratings

}

Replacing the alerts with actual method calls like below doesn't seem to work as expected:

"MySqlJDBC.rate(servletPath, \"1\");"
"MySqlJDBC.rate(servletPath, \"2\");"
"MySqlJDBC.rate(servletPath, \"3\");"
"MySqlJDBC.rate(servletPath, \"4\");"
"MySqlJDBC.rate(servletPath, \"5\");"

While the alerts display correctly, calling the Java methods seems to fail, leaving me puzzled about why the alert works but not the method invocation.

Answer №1

Resolved using JSP code:

"if ($('.star.star-1')[0].checked){" +
                    "   $.ajax({" +
                    "       type: \"POST\"," +
                    "       url: \"" + servletPath + "/servletName\"," +                                      
                    "       data: { operation: \"operation1\", userRating:stars, resId: numberOfQuery }" +    
                    "   }).done(function() {" +
                    "       alert( \"Success\");" +                                         
                    "   });" +
                    "   }" +

and implementing a doPost method in the servlet to execute SQL query.

The correct process is: jsp markup -> jsp function with ajax call -> servlet's doPost method -> JDBC

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

Error: The function setIsEnabled does not exist

Currently, I am in the process of merging two separate next.js projects to create a website that can utilize the Cardano wallet 'Nami'. The code for accessing the wallet functions correctly in its original project, but when transferred over, it p ...

The for loop is throwing an error because the variable 'i' is not defined

I recently started using eslint and I'm in the process of updating my code to comply with my eslint configuration. module.exports = { env: { browser: true, commonjs: true, node: true, es2021: true, }, extends: 'eslint:recomm ...

The operation of executing `mongodb - find()` does not exist as a function

I am having trouble printing all documents from the "members" collection. I attempted to use the find() function, but encountered an error stating that find() is not a function. Here is a snippet from member_model.js located in the models/admin folder: v ...

Creating XML files using Node.js

What are some effective methods for generating XML files? Are there tools similar to the Builder in Rails, or any other recommended approaches? Appreciate any insights! ...

The Jquery.post() function failed to trigger the callback

I'm encountering an issue with the JQUERY Post function. There are 2 functions that utilize the JQUERY Post function. Both of them work fine, but the callback function (handleLike) is not being triggered. Interestingly, when I manually call handleLi ...

Effortlessly transforming a massive JSON into an Array using ReactJS

I have a large JSON dataset containing information on over 2000 cities. I want to use this data in my React app, but first I need to convert it into an array. A similar question has been asked before, but I couldn't find any answers that fit my specif ...

Is client-side JavaScript executed prior to server-side JavaScript in AJAX?

I'm curious about how client-side code interacts with server-side responses. I have a lengthy and complex piece of code that triggers a function which in turn executes some server-side code using a HTTPRequest Object, returning a string to the calling ...

Guide to building a robust tab system using JQuery and Ajax

I am currently working on a mockup page where the accordion feature is functioning well. However, I am looking to implement a tab-like system that will allow users to navigate between different pages. Specifically, I want users to be able to click on page ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Sending properties in NextJS from the server side (Application routing)

In order to share data for each request, I have created an object with this data in the rootLayout. export interface IProps { children: React.ReactNode; data: any; } export default function RootLayout(props: IProps) { const {children} = props; ...

I'm having trouble with my Selenium as it doesn't seem to be able to open

Hey there, I've been working on a script to login to Gmail, but I'm having trouble with entering the password after entering the email. public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", "E:&b ...

The 'import type' declaration cannot be parsed by the Babel parser

Whenever I attempt to utilize parser.parse("import type {Element} from 'react-devtools-shared/src/frontend/types';", {sourceType: "unambiguous"}); for parsing the statement, I come across an error stating Unexpected token, exp ...

Having trouble initiating an AJAX call in Django and returning values to my form

Seeking assistance to run an AJAX call for a quick calculation in my django view and display the result within a span tag on my HTML page. New to Javascript, struggling with triggering my AJAX call. Below is my HTML and JS code: <input type="text" nam ...

Clearing Results Section Using JQuery and Ajax: A Guide to Implementing a Reset Button

Currently, I am diving into the world of Jquery and got stuck on a particular issue. The example I found online consists of a JSP form (a simple addition calculator) and a Servlet that adds two numbers together and displays the result upon clicking the "Ca ...

Is there a way to obtain metadata for a specific link?

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><$BlogPageTitle$></title> <meta property="og:title" content=" ...

Tips on utilizing setInterval in a Vue component

When defining the timer in each individual my-progress, I use it to update the value of view. However, the console shows that the value of the constant changes while the value of the view remains unchanged. How can I modify the timer to successfully change ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...

Passing the value of each table row using Ajax

On my webpage, I have a list of orders displayed. I'm facing an issue where the value of each row in the table is not being passed correctly to my controller and database when a user clicks on a button - it always shows null. Can someone please assist ...

Retrieve the current date and time in JSON format using moment.js for the local

Below is the code snippet I am working with: var startTime = moment("2020-09-08 16:00:00").toDate(); console.log(startTime) const data = {start: startTime} console.log(JSON.stringify(data) After running it, the result is as follows: Tue Sep 08 ...

"Uncaught ReferenceError: $ is not defined in a JavaScript/Vue.js

Currently, I am working on the javascript/vue.js page found at this link. In this file, I have added the following code: $(document).ready(function() { myIP(); }); function myIP() { $.getJSON("//freegeoip.net/json/?callback=?", function(data) { / ...