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

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

Is it possible to deselect a checkbox in a Datagrid Material-ui by clicking a button?

I have set up a grid in Datagrid Material-UI with a checkbox. I am trying to figure out how to uncheck the checkbox by clicking a reset button after it has been checked. For example: This is the DataGrid code I currently have: <DataGrid ...

Trigger the function when the keyboard event is deactivated

Is there a way to continuously run the top set interval whenever I lift my finger from the space key? When I try using the key up event, it only executes that function once. I'm not sure how to implement if/else logic when adding an event listener. se ...

Jest does not recognize AnimationEvent as a defined element

I am currently facing an issue while attempting to simulate an animationEvent for a test within my Angular application. The error message I receive is: ReferenceError: AnimationEvent is not defined. Given that this feature is experimental, it seems like ...

Storing a collection of strings in a MongoDB database: A step-by-step guide

I have come across a few similar questions on stack overflow like this one: How to store an array of Strings in Node MongoDB Mongoose - Save array of strings However, I am unable to understand why my method is not working. I am attempting to save the str ...

Guide to using get() and res.sendFile() function to redirect webpages

Why is the page not redirecting properly? In my index.html file, I have this script: $.get( "/loginPage", function( data ) {}); The purpose of this script is to check if a user is logged in. If they are, it should redirect them to the lobbyPage. This is ...

Implementing OR logic for event handlers with jQuery

I have a dropdown list where I want to make an ajax call on both onchange and onload events. $('#id').change(function() { // ajax call }); Instead of just calling the ajax on change, I also need it to be triggered on page load. My current log ...

Fill the drop-down menu with the present day's date, month, and year

I'm new to this, so please bear with me. I have some html and jQuery code: $(document).ready(function() { var d = new Date(); var month = d.getMonth() + 1; var year = d.getFullYear(); $("#month").val(month); $("#year").val(year) ...

What is the best way to ensure that empty strings are not included in the length of my array?

I have encountered an issue with a JSON file that I fetch. The array syllables is capable of holding up to strings max. However, when I exclude 2 words, I end up with 2 words and 2 empty strings. Nevertheless, my front-end still expects 4 "strings". So, it ...

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

Is it possible to generate a specified number of divs or HTML tags with varying information using ReactJS?

Currently, I am in the process of constructing this website and I have noticed that I have 4 divs that are essentially doing the same thing. However, I find myself copying and pasting these divs 4 times, only making minor changes to 4 bits of information. ...

Is there a way to verify the existence of a specific error in the console?

There seems to be a conflict between a WordPress plugin or code left behind by the previous programmer, causing the WordPress admin bar to always remain visible. While no error is triggered for admins, visitors may encounter a console error. My goal is to ...

Eliminate the use of quotation marks in the AJAX response

The response returned as "4", instead of just 4 I attempted changing it to .done(function(data)) but the outcome remained the same $.ajax({ url: "../api/ajax/addToCart.php", type: "post", data: data }) .done(function(response) { // alert( ...

Developing with Cordova involves collaborating with PHP and MySQL for efficient and seamless

As a newcomer to the world of cordova, I am currently in the process of familiarizing myself with its syntax. At this stage, I have manually inputted some json data and developed an application. In this app, when a user chooses a serial number from a dropd ...

The UpdatePanel is causing interference with controls located outside of its boundary

I am encountering an issue with a basic updatepanel on a webforms page. On the same page, I have some inline expressions outside of the updatepanel. Although the updatepanel updates successfully when triggered, I noticed that during the ajax postback proc ...

Generate an image with PHP and then have it be sent as a response to an AJAX

I am utilizing this code snippet to dynamically generate an image using PHP. $image_width = 120; $image_height = 40; $characters_on_image = 6; $font = '/fonts/OpenSans.ttf'; //The characters that can be u ...

When using setTimeout in NodeJS/Express, a TypeError is thrown stating that it cannot read the property 'client' as it is undefined

My nodejs express route is basic: app.get('/timeout', function (req, res) { setTimeout(() => { console.log('timeout'); }, 2000); res.send({ hello: "world" }); }); However, it's not functioning cor ...

Angular 4: Unhandled error occurred: TypeError - X does not exist as a constructor

I am currently developing a project in Angular 4, and I encountered an error while running the application. The specific error message is as follows - ERROR Error: Uncaught (in promise): TypeError: index_1.EmployeeBase is not a constructor TypeError: in ...

How to implement various middlewares in Express.js depending on the current environment using NODE_ENV?

My dilemma involves utilizing two different middlewares based on NODE_ENV: router1 for production and router2 for testing and development environments. I'm currently using the following code snippet: if( process.env.NODE_ENV === 'prod' ) { ...