Obtain information in JSP from a JavaScript function that was generated in another JSP file

I have created a code that allows the admin to toggle a user's status between active and inactive using radio buttons. The technologies I have used for this project are JSP, MySQL, and JS.

admin.jsp:

    <tr>
                <td>
                  Name:  <% out.println(firstname); %> <% out.println(lastname); %>  

                </td>
                <td>
                    <% if (flag.equals("A")){ %>

                    Active: <input type="radio" value="A" name="<% out.println(email); %>" id="<% out.println(email); %>" onchange="pageupdatecta('<% out.println(email); %>', this.value);" checked>
                    Inactive: <input type="radio" value="I" name="<% out.println(email); %>" id="<% out.println(email); %>" onchange="pageupdatecti('<% out.println(email); %>', this.value);">
                   <%
                        }else if(flag.equals("I")){%>

                    Active: <input type="radio" value="A"  name="<% out.println(email); %>" id="<% out.println(email); %>" onchange="pageupdatecta('<% out.println(email); %>', this.value);">
                    Inactive: <input type="radio" value="I" name="<% out.println(email); %>" id="<% out.println(email); %>" onchange="pageupdatecti('<% out.println(email); %>', this.value);" checked>
<%   
} %>
<script type="text/javascript">
  function pageupdatecta(emailid, optedval) {
       location.href='changeToActive.jsp?email='+emailid+'&optedval='+o‌​ptedval; 
   } 
    function pageupdatecti(emailid, optedval) {
       location.href='changeToInactive.jsp?email='+emailid+'&optedval='+o‌​ptedval; 
   }     
</script> 

changeToActive.jsp:

    try{

Class.forName("com.mysql.jdbc.Driver");
System.err.println("Driver loaded!");

Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost/work", "root", "MyNewPass");
System.err.println("Database Connected..");

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                       ResultSet.CONCUR_READ_ONLY);

stmt.executeUpdate("update assignment set flag='A' where email='"+email+"'");
                                   System.err.println("A"+email);

}

I'm looking for guidance on how to retrieve values from the function and troubleshoot my code. Can you assist with this?

Answer №1

Retrieve a record from the assignment table in the work database for id=1.
The radio button's checked status is determined by the existing status in the DB.

Any changes made from active to inactive or vice versa will be updated in the database.

index.jsp Page:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<%@ page import="java.sql.*,stack.filter.JDBCConnector" %>  
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Radio Select</title>
</head>
<body>
<%
Connection con = null;
String firstname = null;
String lastname = null;
String email = null;
String flag = null;
try {
    con = JDBCConnector.connect_database();
    Statement stmt = con.createStatement();
    ResultSet rs=stmt.executeQuery("select * from assignment where id=1");

    while(rs.next()){
        firstname=rs.getString(2);
        lastname=rs.getString(3);
        email=rs.getString(4);
        flag=rs.getString(5);
    }
    System.out.println(""+firstname+" "+lastname+" "+email+" "+flag);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    con.close();
}
%>
<table>
    <tr>
        <td>
              Name:  <% out.println(firstname); %> <% out.println(lastname);          %>
        </td>
        <td> 
         <%
            if(flag.equals("A")){
                %> Active: <input type="radio" name="<%=email%>" id="r1" value="A" onclick="updateStatus()" checked="checked"/> 
                 In active: <input type="radio" name="<%=email%>" id="r2" value="I" onclick="updateStatus()"/>
                 <%
            }else if(flag.equals("I")){
                %> Active: <input type="radio" name="<%=email%>" id="r1" value="A" onclick="updateStatus()"/> 
                 In active: <input type="radio" name="<%=email%>" id="r2" value="I" onclick="updateStatus()" checked="checked"/>
                 <%
            }
         %>
        </td>
    </tr>
</table>
<script type="text/javascript">
        function updateStatus(){
            if (document.getElementById('r1').checked) {
                location.href='changeToActive.jsp?email='+'${email}'+'&status=A';
            }else if (document.getElementById('r2').checked) {
                location.href='changeToActive.jsp?email='+'${email}'+'&status=I';
            }       
        }
</script>
</body>
</html>

changeToActive.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*,stack.filter.JDBCConnector" %>  
<%
Connection con = null;
try {
    con = JDBCConnector.connect_database();
    System.err.println("Database Connected..");

    Statement stmt = con.createStatement();
    String status = request.getParameter("status");
    String email = request.getParameter("email");
    int i= stmt.executeUpdate("UPDATE assignment SET status='"+status+"' where email='"+email+"'");
    if(i==1){
        out.println("Successfully updated the status");
    }

} catch (Exception e) {
    e.printStackTrace();
}finally{
    con.close();
}
%>

JDBCConnector.java class: used for creating a connection object in your app.

package stack.filter;

import java.sql.Connection;
import java.sql.DriverManager;
public class JDBCConnector {        
public static Connection connect_database(){
    Connection con = null;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/work", "root", "root");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(con!=null)
        {
            System.out.println("Connected...");
        }
    }
    return con;
}
}

Assignment Table:

CREATE TABLE `assignment` (
`id` INT(11) NOT NULL,
`firstname` VARCHAR(30) DEFAULT NULL,
`lastname` VARCHAR(30) DEFAULT NULL,
`email` VARCHAR(30) DEFAULT NULL,
`status` CHAR(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) 

/*Data for the table `assignment` */

INSERT  INTO `assignment`(`id`,`firstname`,`lastname`,`email`,`status`) VALUES (1,'rohit','gaikwad','<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea988582839e8d8b83819d8b8eaa929390c4898587">[email protected]</a>','I');

Note: The id=1 primary key is hardcoded. If there is a logic in place to display assignment records, it will be reflected in the table.

Answer №2

To retrieve the query parameters' values, simply do the following:

String email = request.getParameter("email");
String optedval = request.getParameter("optedval"); 

After obtaining the values, you can integrate them into your SQL query.

Answer №3

Make sure to differentiate the IDs of the radio buttons to avoid conflicts.

Active: <input type="radio" value="A" name="<% out.println(email); %>" id="id1" onchange="pageupdatecta('<% out.println(email); %>');" checked>
Inactive: <input type="radio" value="I" name="<% out.println(email); %>" id="id2" onchange="pageupdatecti('<% out.println(email); %>');">


<script> 
function pageupdatecta(emailid) { 
alert('Hi');
location.href='changeToActive.jsp?email='+emailid; 
} 
function pageupdatecti(emailid) { 
alert('Hi'); 
location.href='changeToActive.jsp?email='+emailid;
} 
</script>

Ensure in your servlet that you use

String email = request.getParameter("email");
to retrieve the email value.

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

Proceed with downloading the file only when a checkbox has been ticked off and the form has been

Is there a way to make a PDF download only when a user checks a checkbox and submits the form, rather than just checking the checkbox and hitting submit? I am limited to using Jquery or plain javascript and do not have access to backend files. The checkbox ...

Print out 5000 entries using PHP and then delete them

I have a requirement to display records from a massive data set consisting of 300,000 entries. The approach would be to display the first 5000 records, then unset($data), and continue iterating until all records in the mysql table are displayed. Here is ...

Implement a dropdown menu in Vue.js using data fetched from an ajax request

I am looking to utilize ajax calls in conjunction with vue.js to dynamically populate the options for a drop-down menu. Here's an example of what I currently have: <select v-model="selected"> <option v-for="option in options" v-bind:valu ...

Encountered a ClassCastException while processing a Firewalled Request in the session management filter of the Spring filter chain

I'm encountering an exception thrown by the session management filter in the Spring filter chain within the HttpSessionSecurityContextRepository class. Below is a snippet from my security-app.xml: <beans:bean id="springSecurityFilterChain1" class= ...

Changing the image source when clicking on it and removing it can be done by using JavaScript

How can I add a class 'selected' to ".swiper-slide" when it is clicked? I also want to change the image src when svg-img1, 2, or 3 is clicked. However, I need the image to revert back to its default src when another swiper-slide is clicked. ...

What is the best way to modify the size of a canvas element while maintaining effectiveness?

I've encountered an issue while using Canvas to create a pie chart with chart.js. Despite adjusting the dimensions of the canvas element, it continues to take up the entire page. <canvas id="myChart" height ="200" width="200"></can ...

Tips on avoiding the accumulation of event handlers when dealing with click events triggered by the document selector in jQuery

I am currently working on a project that involves using AJAX to load various pieces of HTML code. This is done in order to properly position dynamic buttons within each portion of the HTML content. In my case, I need to trigger click events on the document ...

Exploring the concept of $http/$q/promise in Angular

I am struggling to understand when $q/$http should trigger the onReject block. For example, if I have a simple call like this: $http.get('/users') .then(function(res) { return res.data; }, function(err) { console.log(err); }); If ...

What is the process for triggering a PHP function when a form element is clicked in a webpage?

Currently, I am trying to implement a jQuery colorbox on my webpage which appears over a <select> drop-down list. My goal is to trigger an AJAX call every time a new option is selected from the drop-down. Even though I have written the following cod ...

Increase the value of count (an AJAX variable) by 4 upon clicking the button, then send it over to the PHP script

I'm facing an issue where my AJAX variable is only updating once by +4 each time a button is pressed. I need assistance on how to make it continuously work. index.php - AJAX <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.m ...

Vue verifies the readiness of two computed properties

Each time I want to determine when multiple computed values are ready, I create another computed property like isFizzAndBuzzReady. computed: { fizz () { return ['f', 'i', 'z', 'z'] // asynchronous data retriev ...

Enhance Your MUI React Component with Custom Styles and ThemeProvider Integration

Currently, I am delving into the world of MUI components within a React environment. Specifically, I am utilizing MUI 5 and React 17. These MUI components are sourced from a third-party library, resulting in limited direct access. My current goal is to rev ...

What is the best way to retrieve a style property from a <style> tag using JavaScript?

Is there a way to retrieve CSS properties set in the <style> tag in JavaScript, rather than just those set in the element's style attribute? For example: <style> div{background:red;} </style> How can I access these styles, such ...

Converting an Array of Users to an Array of Email Addresses Using Google Apps Script

I am currently in the process of creating a script using Google Apps Script. My goal is to verify whether a user with the email address [email protected] has viewing or editing privileges for a folder. If the user does not have either privilege, I wa ...

Dynamic Binding of Checkboxes in Vuex

I am encountering a problem with binding checkboxes using Vuex. Even though I am using v-model with a variable that has a getter and setter to set or get the value in the store, I keep getting incorrect data in the store. The issue arises when I click on a ...

Guidelines for sending data as an array of objects in React

Just starting out with React and I have a question about handling multi select form data. When I select multiple options in my form, I want to send it as an array of objects instead of an array of arrays of objects. Can anyone help me achieve this? import ...

What is the reason behind Selenium's inability to locate XUL buttons?

I have been working on automating tests for a Firefox add-on using Selenium, specifically the insecure-links-highlighter add-on. However, I am facing an issue where it cannot locate the "Preferences" button in about:addons: extensionEntry.findElement(By.c ...

Display information from an array in checkboxes. If the same data appears in another array, the corresponding checkbox in React will be automatically checked

I currently have two arrays. The first array, let's call it arr1, contains multiple objects such as [{"Name":"Mr.X"},{"Name":"Mr.Y"},{"Name":"Mr.Z"}]. The second array, named arr2, holds a few values like [{"Name":"Mr.Z"}]. My goal is to display all ...

Discovering a way to capture the space bar event in a number input field with JavaScript

Is there a way to capture space bar input with an onchange event in JavaScript? <html> <head> <script type = "text/javascript"> function lala(aa){ console.log(aa + " dasda"); } </script> </head> <body> <input ty ...

Switch the placement of two DIV elements by their corresponding IDs

I am attempting to adjust the position of two divs using jQuery, but I seem to be a bit confused as they are already swapping positions. However, when they do swap, it results in a duplication of the field. I have tried using both insertBefore and insertA ...