Database changes in radio button in jsp - mysql

I have written a code where the admin has the access to change the general users from active to inactive and vice-versa. So I want to update the database if the radio button is changed from active to inactive.
Here is the code:
<%
while (rs.next()) {
String firstname = rs.getString("firstname");
String lastname = rs.getString("lastname");
String email = rs.getString("email");
String password = rs.getString("password");
String age = rs.getString("age");
String sex = rs.getString("sex");
String haddress = rs.getString("haddress");
String oaddress = rs.getString("oaddress");
String phonenumber = rs.getString("phonenumber");
String flag = rs.getString("flag");
Statement stmt1 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
%>
<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); %>" onclick="<% stmt1.executeUpdate("update assignment set flag='A' where email='"+email+"'");
System.err.println("A"+email); %>
alert('changed to active');" checked>
Inactive: <input type="radio" value="I" name="<% out.println(email); %>" onclick="<% stmt1.executeUpdate("update assignment set flag='I' where email='"+email+"'");
System.err.println("I"+email); %>
alert('changed to inactive');">
<%
}else if(flag.equals("I")){%>
Active: <input type="radio" value="A" name="<% out.println(email); %>" onclick="<% stmt1.executeUpdate("update assignment set flag='A' where email='"+email+"'");
System.err.println("A"+email); %>
alert('changed to active');">
Inactive: <input type="radio" value="I" name="<% out.println(email); %>" onclick="<% stmt1.executeUpdate("update assignment set flag='I' where email='"+email+"'");
System.err.println("I"+email); %>
alert('changed to inactive');" checked>
But in output, when I change one radio button, all the queries run automatically, updating the database to I for all the data in the DB.

Using onclick, you need to invoke a ajax call and update the response . You should not use like onclick="<%SOME SQL Query%>". That is why it's updating all the rows.
Step 1:
" onclick="updatestatus(this.value, '<% out.println(email); %>')"/>
Step 2 :
Add Jquery lib and add a JS function
function updatestatus(statuschg, email) {
/*ajax call to some update-status.jsp with email and current value needs to be passed */
//ajax code goes here ...
$.ajax({
type: "post",
url: "update-status.jsp", //this is my servlet
data: "email=" +email"&status="+statuschg,
success: function(msg){
alert(msg);
}
});
}
Ref: How to invoke ajax call How to pass parameters in GET requests with jQuery
step 3:
i) In update-status.jsp,Establish db connection
ii) receive parameters of the email address and current status.
iii) Execute the Query
stmt1.executeUpdate("update assignment set flag='+status+' where email='"+email+"'")
iv) out.println("Updated");

You are mixing two different codes. The key is to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is send to the browser) and Javascript in the browser, after the browser receives the already generated response.
I.e. in your
onclick="<% stmt1.executeUpdate("update assignment set flag='I' where email='"+email+"'"); System.err.println("I"+email); %> alert('changed to inactive');"
the <% stmt1.executeUpdate("update assignment set flag='I' where email='"+email+"'"); System.err.println("I"+email); %> part is executed on the server when the page is generated, and only the alert('changed to inactive'); waits in browser until the input field is clicked.
What you need is AJAX.
Side note: Do not put Java code into JSP, use MVC pattern, or at least put the code into an "util" class and call the class from JSP.

Related

if statement not executed in JSP scriptlet

i encountered the following problem. I have made a table in mysql named 'users' and i want to add users using JSP. The primary key is the Email and i want to check before adding another user if the email already exists. If the email already exists the users will not be added to the database and a message "email already exists" will appear.
I created ResultSet rs object and extracted the "Email" column into a String email using a while loop.Now, here comes the problem. Suppose i have a user with the "denis#yahoo.com" email. If i try to add an user with the exact same email an error will occur which means my if statement was ignored. I looked up in the debug mode for the variables email and Email and they had the exact same "denis#yahoo.com" and still the if statement was ignored.
<!-- file name: addUser.jsp -->
<%
String Email=request.getParameter("Email");
String Name = request.getParameter("Name");
String Adress = request.getParameter("Adress");
String Phone = request.getParameter("Phone");
if (Email != null)
{
jb.connect(); // connect to the database using JavaBean class
ResultSet rs;
rs=jb.seeTable("users");// rs gets first row of table
String email;
int a=1;
while(rs.next())
{
email=rs.getString("Email");
if(Email==email)
{
a=0;
jb.disconnect();
%>
<p> The email already exists</p>
<%
break;
}
}
if(a==1){
jb.addUser(Email,Name, Adress, Phone);
jb.disconnect();
%>
<p>Data has been added.</p>
<%
}
} else {
%>
<form action="addUser.jsp" >
Email: <input type="text" name="Email"><br>
Name: <input type="text" name="Name"><br>
Adress: <input type="text" name="Adress"><br>
Phone: <input type="text" name="Phone"><br>
<button type="submit" >Add User</button><br>
</form>
<%
}
%>
I use NetBeans IDE 8.2, and something that i think is odd appeared in the debug mode. One of the email i try to test appeared with bold characters meanwhile the other was not bold.
Why is my if statement ignored if i add an user with the exact same email of another? Please help me out!

Submit a 'null' to a jsp from an html form

Forwarding an html form to a jsp page which has an
<input type="text" name="name">
for 'name' parameter to be processed in jsp page. When no name is supplied , I do want the form to be submitted to the jsp and jsp should detect 'null' to process an if-else loop to display a relevant message.
How do I achieve that?
I do want the form to be submitted to the jsp and jsp should detect
'null' to process an if-else loop to display a relevant message.
You can use this on your display.jsp page to check if value is not null and not empty:
<%
String name = request.getParameter("name");
if(name != null && !name.isEmpty()){
%>
<p>name is <%=name%></p>
<%
}else{
%>
<p>name is null or empty!</p>
<%
}
%>
But as mentioned already this is highly discouraged! You should be using a servlet. If you want to see how that can be done, let me know and i'll edit this answer with a better solution.

Unable to fetch the data of a column with radio buttons in jsp using servlet with request.getParameterValues() function

I have a table with 3 columns.Last column has 4 radio buttons in each row.I am not able to fetch all the values of radio buttons checked after submitting the form.I always get only one value which is the value of radio button checked in the first row.
Here is the code of jsp page:
<form action = "SaveData" method = "POST" target = "_blank">
<h1>LIST</h1>
<%
try {
/* Create string of connection url within specified format with machine
name, port number and database name. Here machine name id localhost and
database name is student. */
String connectionURL = "jdbc:mysql://localhost:3306/sample";
// declare a connection by using Connection interface
Connection connection = null;
/* declare object of Statement interface that is used for executing sql
statements. */
Statement statement = null;
// declare a resultset that uses as a table for output data from tha table.
ResultSet rs = null;
// Load JBBC driver "com.mysql.jdbc.Driver"
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection() method that takes parameters
of string type connection url, user name and password to connect to database.*/
connection = DriverManager.getConnection(connectionURL, "root", "password");
/* createStatement() is used for create statement object that is used for
sending sql statements to the specified database. */
statement = connection.createStatement();
// sql query to retrieve values from the secified table.
String QueryString = "SELECT * from data";
rs = statement.executeQuery(QueryString);
%>
<table class="comparison-table">
<tr>
<th>LIST</th>
<th>Y/N</th>
<th>OPTIONS</th>
</tr>
<div>
<tr>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<form>
<input type="radio" name="option" value="a" checked> A
<input type="radio" name="option" value="b" >B
<input type="radio" name="option" value="c" > C
<input type="radio" name="option" value="d"> D
</form>
</td>
</tr>
</div>
<% } %>
<%
// close all the connections.
rs.close();
statement.close();
connection.close();
}
catch (Exception ex) {
%>
<%
out.println("Unable to connect to database."+ex);
}
%>
</table>
<button value="Submit" id="button">Submit</button>
</form>
Here is the Servlet code:
import javax.servlet.annotation.WebServlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
//Extend HttpServlet class
#WebServlet("/SaveData")
public class SaveData extends HttpServlet {
// Method to handle GET method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Form Parameters";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"+
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
}
Output after submitting the form would be values of two parameters "choose" and "option". I get proper output for "choose" parameter ie. all the selected Yes/No options in a cloumn,whereas for "option" parameter i would get only the value of first row selected radio button ie if i select 'c' in the first row radio buttons only 'c' will be displayed with rest of the rows ignored.
Please help me out in fetching data of all the columns of the radio buttons selected in a String array.
I also want to fetch the value of "slist" which is from database using servlet. This is under td tag with name="list".
First you sould not nest form tag, remove the form tag before radio button.
From MDN web docs :
elements of type radio are generally used in radio
groups—collections of radio buttons describing a set of related
options. Only one radio button in a given group can be selected at the
same time.
You should add a variable to differentiate lines like this for example :
<tr>
<%! int lineNumber = 0 %>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<input type="radio" name="option<%= lineNumber %>" value="a" checked> A
<input type="radio" name="option<%= lineNumber %>" value="b" >B
<input type="radio" name="option<%= lineNumber %>" value="c" > C
<input type="radio" name="option<%= lineNumber %>" value="d"> D
</td>
</tr>
<% lineNumber++ %>

Delete query using jsps

I'm new to JEE programming, I know that the way I present you my problem is not optimal but I have to do it using only JPSs first.
So, I created a form that included checkboxes. I would like to delete all members that have been checked. My tag action form redirects to dispaly.jsp where I perform delete query before redirecting to my main page, members.jsp.
The problem is that my server crash and does not redirect me. I have to restart it, But my rows have been deleted in my database.
Here's my code :
<form method="post" action="display.jsp"><table id="members_table">
<tr>
<th>Sel</th><th>FIRSTNAME</th><th>NAME</th><th>EMAIL</th>
</tr>
<%
while (resultset.next()) {
%>
<tr>
<td><input type="checkbox" name="selected" value="<%=resultset.getString(1)%>"/></td>
<td><%= resultset.getString(2)%></td>
<td><%= resultset.getString(3)%></td>
<td><%= resultset.getString(4)%></td>
</tr>
<%}%>
</table>
<input type="submit" value="Details" name="details" id="details_members">
<input type="submit" value="Delete" name="delete" id="delete_members">
</form>
display.jsp page :
RequestDispatcher requestDisp = request.getRequestDispatcher("/members.jsp");
if(request.getParameter("delete") != null)
{
if(request.getParameter("selected")!=null)
{
String[] a = request.getParameterValues("selected");
str = "DELETE FROM MEMBERS WHERE ID = ";
for(int it=0;it<a.length;++it)
{
if(it==a.length-1)
str+=a[it];
else
str+=a[it]+" OR ID = ";
}
statement.executeUpdate(str);
requestDisp.forward(request, response);
}
requestDisp.forward(request, response);
}
When I run my code, I get this error after a long time waiting :
javax.servlet.ServletException: java.sql.SQLTransactionRollbackException: Unable to get a lock within the requested timeout
root cause
java.sql.SQLTransactionRollbackException: Unable to get a lock within the requested timeout
I don't understand why my server crash, I tried to execute this delete query directly in my database and it works. I also debug my code to see if my variable "str" contains right query ...
Please help.

How can I save each item in a "select multiple" field in its own MySQL record (using Rails)?

Thanks for any help you can provide! I have a Ruby on Rails application where I am trying to save maps with driving directions and waypoints. The data needs to come straight out of the entry form instead of the Google Maps javascript. I've solved the starting and ending points, but the waypoints are giving me a problem.
My questions:
How can I save each waypoint in its own record in the Waypoint table? I'm able to get the first waypoint into the table, but the rest of the "select multiple" options are ignored.
How can I make each waypoint.newsavedmap_id field the same as its corresponding newsavedmaps id so that I can call these up later?
HTML
<p>Enter a street address, city, and state:
<input id="startinput" type="text" name="starthere" size="56"></p>
<p>Or, select a location from the list:
<select id="startdrop" name="startthere">
<option value="">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select></p>
<div><b>Stops</b></div>
<div id="multiselectdiv1">
<select multiple id="waypoints" name="waypointsselected">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select>
</div>
<b>End</b>
<p>Enter a street address, city, and state:
<input id="endinput" type="text" name="endhere" size="56"></p>
<p>Or, select a location from the list:
<select id="enddrop" name="endthere">
<option value="">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select></p>
</div>
<div>
<input type="submit" onclick="calcRoute();" id="showmapview" value="Show Map">
</div>
I have two MySQL tables. The first is newsavedmaps:
id
itinerary_id
start
start_lat
start_long
start_masterlocation_id
end
end_lat
end_long
end_masterlocation_id
name
The second is waypoints:
id
newsavedmap_id
waypoint
waypoint_lat
waypoint_long
waypoint_masterlocation_id
The two are meant to be connected by newsavedmaps.id and waypoint.newsavedmap_id .
My newsavedmap_controller.rb includes:
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
#newsavedmap.name = params[:newsavedmapname]
if !params[:starthere].blank?
#newsavedmap.start = params[:starthere]
else
#newsavedmap.start = params[:startthere]
end
if !params[:endhere].blank?
#newsavedmap.end = params[:endhere]
else
#newsavedmap.end = params[:endthere]
end
if !params[:waypointsselected].blank?
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
end
Edit 1
In response to Colinm's suggestion to wrap the controller in an iterator to get separate records for each address, I tried this, but I'm pretty sure I'm doing the wrong thing:
if !params[:waypointsselected].blank?
for waypoint in #waypoint
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
#waypoint.newsavedmap = #newsavedmap
end
end
How can I save each waypoint in its own record in the Waypoint table? I'm able to get the first waypoint into the table, but the rest of the "select multiple" options are ignored.
Unless you have a really good reason not to, use Rails' form helpers instead of rolling your own form fields. They will take care of this automatically, as well as handle edge cases you may not even know about. (Like the gotcha that sending a multiple select back with no selections will leave the record unchanged. That doesn't sound like it's an issue in your use case, but Rails still has your back if you use the form helpers.)
In your case, you'd simply pass multiple: true in the html_options hash, like so:
<%= f.select :waypointsselected,
MasterLocation.waypoints_for_select,
{},
{ multiple: true }
%>
Note that this does assume you implement a waypoints_for_select method. Without seeing all the code, it looks like you have way too much logic in your view right now. It's brittle and verbose to construct the options array in the view; offloading that to the model or a helper keeps your view code cleaner and helps eliminate potential future bugs.
If you absolutely can't/absolutely don't want to use form helpers in this application, the key you're looking for is []. Rails sensibly assumes a form field represents a single value unless you explicitly denote it as an array. Just tack an empty array on the end of the field name:
<select multiple id="waypoints" name="waypointsselected[]">
...and that field's key in the params hash will instead contain an array of values representing the selected items:
{ waypointsselected: ["3", "6", "9"] }
As for associating the waypoints with the newsavedmaps, just set it explicitly during creation. You're almost there:
if !params[:waypointsselected].blank?
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
# You can do it like this...
#waypoint.newsavedmap = #newsavedmap
# Or using the ID...
#waypoint.newsavedmap_id = #newsavedmap.id
end
(I haven't adapted this code to deal with the fact you now have an array of values in waypointsselected; I just plugged the relationship definitions into your existing code. Remember to adjust your code to expect an array and iterate over it.)