Retrieve your username data using Ajax

I'm working on a JSP page with the following structure:

https://i.sstatic.net/3aFoz.png

In updating the table in my database, I've added a new username column that accepts any string of text. Once the 'update user' button is clicked, it should trigger the database update.

The database table has a unique column named AUSERNAME where the usernames are stored as seen in the screenshot. After clicking the update button, the goal is to pass the new username value and update the corresponding field in the table.

To achieve this, I understand that an AJAX call needs to be made within the JSP page. Below is the snippet of code for the AJAX call:

 <script >
    function update(param,param1) {


        var newuser = document.getElementsByName('NewUserName' + param)[0].value;
        var currentuser = document.getElementsByName(param1).value;



        $.ajax({
            type: "POST",
            url: "update.jsp",
            data: { name: newuser,
                current: currentuser

            },
            success:function( msg ) {
                alert( "Data Updated: " + msg );
            },error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });

    }




</script>

<form method="get" action="migratefolder.jsp">

    <%



        try {



            Class.forName("com.mysql.jdbc.Driver");
            String connectionURL = "jdbc:mysql://localhost:3306/gmc";
            String username = "root";
            String password = "root";
            Connection conn = null;

            conn = DriverManager.getConnection(connectionURL, "root", "root");

            String query = "select ausername, ausertype from auser where AUSTATE='Y'";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            String str = "<table border=2><tr><th>Username</th><th>New Username</th><th>User Type</th><th>Update</th></tr>";
              int rowid = 0;
  String currentuser=null;
            while (rs.next()) {
                rowid ++;

            currentuser=rs.getString("ausername");
                String autype = rs.getString("ausertype");
                str += "<tr><td><input readonly type=\"value\" name=\""+currentuser+"\" value="+rs.getString("ausername")+" </td><td><input type=\"text\" name=\"NewUserName"+rowid+"\""+
                        "value=\"\"></td> <td>";

                if (autype.equalsIgnoreCase("Superuser")) {
                    str += "<input type=\"radio\" name=\"usertype"+rowid+"\"  value=\"Superuser\" checked> Superuser ";
                }else{
                    str += "<input type=\"radio\" name=\"usertype"+rowid+"\" value=\"Superuser\" > Superuser ";
                }
                if(autype.equalsIgnoreCase("Basic")) {
                    str += " <input type=\"radio\" name=\"usertype"+rowid+"\" value=\"Basic\"  checked > Basic ";
                }else {
                    str += " <input type=\"radio\" name=\"usertype"+rowid+"\" value=\"Basic\"   > Basic ";
                }
                if(autype.equalsIgnoreCase("View")){
                    str += " <input type=\"radio\" name=\"usertype"+rowid+"\" value=\"View\"  checked> View ";
                }else {
                    str += " <input type=\"radio\" name=\"usertype"+rowid+"\" value=\"View\"  > View ";
                }
                str += "</td><td><button type=\"button\" onclick=\"update("+rowid+","+currentuser+")\">Update User</button></td> </tr>";


            }










            out.println(str);
            rs.close();
            stmt.close();
            conn.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    %>

Currently, my update.jsp page looks like this:

  <% response.setContentType("text/xml");%>

<%

    String userid=request.getParameter("current");
    String user=request.getParameter("name");
//database connection
    try{
        Class.forName("com.mysql.jdbc.Driver");
    }
    catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Connection con=null;
    ResultSet resultSet=null;
    Statement stmt=null;

    int row=0;

    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/gmc", "root", "root");
        String sql = "UPDATE `auser` SET `AUSERNAME`=? WHERE `AUSERNAME`=? ";
        PreparedStatement statement = con.prepareStatement(sql);
        statement.setString(1, user);
        statement.setString(2, userid);
         statement.executeUpdate();

    }
    catch (Exception ex) {
        ex.printStackTrace();


    }

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");



%>

My challenge lies in specifying the constraint on the current username itself for the update process. The current username values are fetched using a result set loop. For instance, I need to instruct the table to update the username to test with the constraint being USER1.

Is there a way for me to retrieve the Username value in my update function?

Answer №1

There is a small modification needed in the update function to successfully pass the value.

In order to pass the value in the JavaScript function, follow this format:

<button onclick=update('abc','bcd')></button>

Take a look at the code snippet below.

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<script>
    function update(param, param1) {
        var newuser = document.getElementsByName('NewUserName' + param)[0].value;
        var currentuser = param1;

        $.ajax({
            type : "POST",
            url : "update.jsp",
            data : {
                name : newuser,
                current : currentuser
            },
            success : function(msg) {
                alert("Data Updated: " + msg);
                location.reload();
            },
            error : function(xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }
</script>

<form method="get" action="migratefolder.jsp">

    <%
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String connectionURL = "jdbc:mysql://localhost:3306/test";
            String username = "root";
            String password = "root";
            Connection conn = null;

            conn = DriverManager.getConnection(connectionURL, "root", "root");

            String query = "select ausername, ausertype from auser where AUSTATE='Y'";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            String str = "<table border=2><tr><th>Username</th><th>New Username</th><th>User Type</th><th>Update</th></tr>";
            int rowid = 0;
            String currentuser = null;

            while (rs.next()) {
                rowid++;
                currentuser = rs.getString("ausername");
                String autype = rs.getString("ausertype");

                // Building the HTML table rows dynamically
                str += "<tr><td><input readonly type=\"value\" name=\"" + currentuser + "\" value="
                        + rs.getString("ausername") + " </td><td><input type=\"text\" name=\"NewUserName" + rowid
                        + "\"" + "value=\"\"></td> <td>";

                if (autype.equalsIgnoreCase("Superuser")) {
                    str += "<input type=\"radio\" name=\"usertype" + rowid
                            + "\"  value=\"Superuser\" checked> Superuser ";
                } else {
                    str += "<input type=\"radio\" name=\"usertype" + rowid + "\" value=\"Superuser\" > Superuser ";
                }

                if (autype.equalsIgnoreCase("Basic")) {
                    str += " <input type=\"radio\" name=\"usertype" + rowid
                            + "\" value=\"Basic\"  checked > Basic ";
                } else {
                    str += " <input type=\"radio\" name=\"usertype" + rowid + "\" value=\"Basic\"   > Basic ";
                }

                if (autype.equalsIgnoreCase("View")) {
                    str += " <input type=\"radio\" name=\"usertype" + rowid + "\" value=\"View\"  checked> View ";
                } else {
                    str += " <input type=\"radio\" name=\"usertype" + rowid + "\" value=\"View\"  > View ";
                }

                str += "</td><td><button type=\"button\" onclick=\"update(" + rowid + ",'" + currentuser + "')\">Update User</button></td> </tr>";
            }

            out.println(str);
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    %>

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

Is it necessary to reload the page each time to see updates on the navbar in nextjs?

I recently developed a Next.js application with a Navbar component integrated into my layout.tsx file. The challenge arises when a user logs in and is redirected to the home page, which showcases a link in the Navbar for viewing their profile. However, I n ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

Storing data with NPM global packages: Best practices

I have developed a global npm package that functions as a CLI tool. https://i.sstatic.net/PdT3Z.png My goal is to customize the user experience by having the package remember the user's previous choices. For example, if the user selects 'Iphone ...

Facing issues with Heroku and Express/Nodejs crashing?

I have been working on a React/Express application that I am attempting to deploy on Heroku. While trying to do so, I encountered the following errors in my logs: 2020-01-13T03:39:48.733455+00:00 heroku[router]: at=error code=H10 desc="App crashed" method ...

Reduce the size of log messages in cypress

I am looking to shorten the cypress messages to a more concise string, for instance: Cypress log Transform to: -assert expected #buy-price-field to have value 17,169.00. Is there a way to achieve this? I have searched through the documentation but hav ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

AngularJs - The ngRepeat directive is experiencing significant delays in rendering data

Currently, my application is pulling 100 items per page and implementing a custom pagination solution by making AJAX calls for the next set of items. The data retrieval process takes around 400ms, however, there seems to be a delay in rendering the displ ...

Create automated scripts with Selenium using the programming language JavaScript

Is it possible to create selenium webdriver scripts using only javascript? If so, what are the benefits of choosing javascript over languages like java or C#? In what situations would javascript be the preferred option? Appreciate your insights. ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Direct all clients to a specific page each (where each client is represented by a SessionScoped ManagedBean)

I am managing a page with multiple users (Client 1, Client 2, ...) and I want the action of pressing the "Exit Meeting" button (Button 1) to redirect all clients to a home page (http://localhost:8080/FasMe/faces / Public / Inicio.xhtml). Each client is re ...

What are your thoughts on the practice of utilizing the useState hook within a component to send data to its parent component?

I have been working on developing an Input component that can be dynamically used in any page to store input values. The component also includes an attribute called getValue, which allows the parent component to access the input value. In my App.js file, I ...

Tips on how to direct the attention to a text box within a unique dialog, ensuring that the blinking cursor highlights the input area

Is there a way to set autofocus on a textbox when opening a custom dialog box? I've tried using the autofocus attribute for the input field, but it doesn't seem to work for me. Can anyone provide guidance on how to achieve autofocus for a textfie ...

Enhance Your jQuery Experience with Advanced Option Customization

I am currently developing a plugin that deals with settings variables that can be quite deep, sometimes reaching 3-4 levels. Following the common jQuery Plugin pattern, I have implemented a simple method for users to update settings on the go using the not ...

Setting up AJAX path for SimpleHTTP server with GET method

I'm facing an issue with passing a string stored in a variable called request_str to a SimpleHTTP python web server using AJAX. I am unsure of the process of connecting my AJAX request to the SimpleHTTP server. Here is the AJAX setup I have implement ...

Phalcon PHP encountered issues with CSRF token validation during AJAX requests

I am currently utilizing the Phalcon Framework and have decided to incorporate the CSRF function provided. Following the steps outlined in the documentation, I have successfully implemented it. Upon receiving the data along with the token and its value, I ...

Issue: The variable THREE has not been defined within the FBXLoader code

Currently, I am utilizing the module version of three.js in order to execute imports from a client-side JavaScript file structure. The core functionality of THREE is working correctly. However, I am encountering an issue when attempting to use it with FBX ...

What is the best way to display data from a dynamically generated table in a popup window?

My table is dynamically populated with the following JavaScript code: $(document).ready(function (e) { var t = { Qty: [61.0, 0.0, 8.0], Name: ["2009 A", "2009 B", "2009 C "] } $.each(t.Qty, function (i, ele) { $("#content") ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Utilize the bodyParser middleware within a middleware to handle the request body parsing

Currently, I am developing an Express app where most routes have a limited body size except for admin users who require unlimited body size for certain routes. To manage this, I implemented a middleware called limitBodySize using the following syntax: app. ...

Having trouble retrieving the state name within the directive controller

When trying to access $state.current.name from a directive controller, it always appears to be blank. Is it possible that the directive loads before the state evaluation process? If so, what would be a suitable workaround for this issue? The goal is to dis ...