I want to have Edit and Delete button to delete DB records in one HTML page with JSP. I tried the below code. But only the first button is working ( Whichever I put on the top) and the second one is not working. Could any one help..?
<%# page import="java.sql.*" %>
<html>
<head>
<script language="javascript">
function edit(regno){
var f=document.form;
f.method="post";
f.action='edit.jsp?regno='+regno;
f.submit();
}
function delete(regno){
var f=document.form;
f.method="post";
f.action='delete.jsp?regno='+regno;
f.submit();
}
</script>
</head>
<body>
<form method="post" name="form">
<table border="1">
<tr><th>Name</th><th>Address</th><th>Edit</th><th>Delete</th></tr>
<%
Connection conn = null;
int sumcount=0;
Statement st;
try{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:mydb1");
String query = "select * from student";
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
%>
<%
while(rs.next()){
%>
<tr>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><input type="button" name="delete" value="Delete"
onclick="delete(<%=rs.getString(1)%>);"> </td>
<td><input type="button" name="edit" value="Edit"
onclick="edit(<%=rs.getString(1)%>);"> </td>
</tr>
<%
}
%>
<%
}
catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
Demo: http://jsfiddle.net/6mGzj/
Below example works fine, you can check in console where form is sended after button is clicked.
<form method='post' id='form'>
<table>
<tr>
<td><input type='button' data-action='delete' data-regno='2' value='delete' /></td>
<td><input type='button' data-action='edit' data-regno='3' value='edit' /></td>
</tr>
</table>
</form>
var form = document.getElementById('form');
form.addEventListener('click', function(e) {
var type = e.target.getAttribute('data-action'),
regno = e.target.getAttribute('data-regno');
//console.log(type+'.jsp?regno='+regno);
form.action = type+'.jsp?regno='+regno;
form.submit();
}, false);
There is something wrong with values passed via onclick function in your code. You need to change it from
onclick="delete(<%=rs.getString(1)%>);"
to
onclick="delete('<%=rs.getString(1)%>');"
And check this regno in your javascript function by using either alert(regno); or console.log(regno);
And one more suggestion. You are using scriptlets in your jsp code. Its highly discouraged. you need to start learning JSTL and EL avoid using scriptlets. Hope this helps..
Related
I have a HTML file named Track.html, it contains a text box. We enter a 10 digit number and click the button to search. After validation an AJAX function is called, which sends the number to a jsp file and the input number is searched in the database, if the value is found in the database, the output should be displayed in another text box on the same HTML page(without changing the URL). But the problem is that it is not working.
To check that my jsp file is working properly, I did the following:
I'm using a form tag so in its action attribute I mentioned the jsp file and not calling the AJAX function, so after searching the input number it redirects to a new page and displays the corresponding content fetched from the database, but I want the content to be displayed on the same page.
Here is the HTML part:
<fieldset>
<form method="post">
<table cellpadding="10" cellspacing="10">
<tr>
<td><strong>Consignment Number</strong></td>
<td><input type="text" id="cons" name="cons" autofocus="true"
placeholder="Enter the 10 digit Consignment Number"
</td>
</tr>
<tr>
<td align="center"><button onclick="search()
<span>Search</span></button></td>
<td><span><input type="reset"></span></td>
</tr>
</table>
</form>
</fieldset>
<br>
<fieldset>
<table cellpadding="10" cellspacing="10">
<tr>
<td><strong>Your Package is at:</strong></td>
<td><input type="text" id="result"></td>
</tr>
</table>
</fieldset>
Here is the AJAX function:
function search() {
if (validate()) {
var cnum = document.getElementById('cons').value;
var obj1 = new XMLHttpRequest();
obj1.onreadystatechange = function () {
if ((obj1.readyState == 4) && (obj1.status == 200)) {
document.getElementById("result").value = obj1.responseText;
}
}
obj1.open("get", "Trace.jsp?cn=" + cnum, true);
obj1.send();
}
Here is the jsp code:
<%#page import="java.sql.*"%>
<%
try
{
int conum=Integer.valueOf(request.getParameter("cn"));
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/postal_info","root","*******");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from trace;");
while(rs.next())
{
int c=rs.getInt(3);
if(conum==c)
{
out.println(rs.getString(6));
}
}
}
catch(Exception e)
{
out.println(e);
}
%>
I have a small problem. Right now I'm programming a website, which is connected to a mysql database.
I created a table filled with products, which are stored in the database. Each row has a Button "Add to Cart" but how do I exactly get the specific item for it? I already have the function addtoCart(string articleName) but I don't know how to get the name of the product.
This is what I've got so far:
<table id="Products">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Stock</th>
</tr>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop", "root", "12345");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT* FROM products WHERE category='shisha'");
while(rs.next()){
int id = rs.getInt("articleID");
String pname = rs.getString("productName");
String description= rs.getString("description");
float price = rs.getFloat("price");
int stock = rs.getInt("stock");
%>
<tr>
<td><%out.print(id);%></td>
<td><%out.print(pname);%></td>
<td><%out.print(description);%></td>
<td><%out.print(price);%></td>
<td><%out.print(stock);%></td>
<td> </td>
<td><input type="text" placeholder="How much ?" name="quantity" required> </td>
<td> <input class="button" type = "submit" value="Add to cart"> </td>
</tr>
<%
}
%>
</table>
So it generates a row for each product with its own button.... I want to call the function addtoCart(string articleName) but how do I get the product name of the row the button is in?
Using Jquery you could add a class and data attribute to your button, you could then get the value like so.
<input class="button" data-product="<%out.print(pname);%>" type = "submit" value="Add to cart">
$('.button').click(function(){
var product = $(this).data("product");
addtoCart(product);
});
I hope this helps.
Thanks
add it to the button. Instead of making the button a submit button, create a
<button onclick="addToCart(%out.print(id);%);">Add to cart</button>
then get the product information in a function called addToCart
I just wanted to upload the image using form in JSP, for that I have written a code, as per below code, it is not inserting in while loop. resultant Image is not getting uploaded in directory.
Can you please help to figure out the problem?
html code
<html>
<head><title>Upload page</title></head></p> <p><body>
<form action="upload_jsp.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
<center>
<table border="2">
<tr>
<td align="center"><b>Multipale file Uploade</td>
</tr>
<tr>
<td>
Specify file: <input name="file" type="file" id="file">
<td>
</tr>
<tr>
<td>
Specify file:<input name="file" type="file" id="file">
</td>
<tr>
<td>
Specify file:<input name="file" type="file" id="file">
</td>
</tr>
<tr>
<td align="center">
<input type="submit" name="Submit" value="Submit files"/>
</td>
</tr>
</table>
<center>
</form>
</body>
</html>
jsp code
<%# page import="java.util.List"%>
<%# page import="java.util.Iterator"%>
<%# page import="java.util.ResourceBundle" %>
<%# page import="java.io.File"%>
<%# page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%# page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%# page import="org.apache.commons.fileupload.*"%>
<%
String path= "C:\\Users\\gur29175\\Desktop" ;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
String directory="";
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
} else {
try {
String itemName = item.getName();
File savedFile = new File(path+itemName);
//File savedFile = new File("C:\\Users\\sagar\\Desktop\\JAVA Training\\code(1)\\test\\WebContent\\WEB-INF\\uploads\\"+itemName);
//File savedFile = new File(config.getServletContext ().getRealPath("/")+"uploadedFiles/"+itemName);
item.write(savedFile);
//out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath
//("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+path+
("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
%>
This is the line of code that might be problematic, as item.getName() will return the full path where the source file is located. This might result to a malformed file path.
Try replacing:
String itemName = item.getName();
with:
String itemName = FilenameUtils.getName(item.getName());
Make sure FilenameUtils is imported:
<%# page import="org.apache.commons.io.FilenameUtils" %>
and you have commons-io.jar in your Web app libraries.
Following is the code, where the button Generate Key is getting created dynamically. For each record I get from the table, I create a button against it on the page. I want to capture which button was clicked and then use the values in that row to manipulate something.
<table border="1" width="100%" cellpadding="0" cellspacing="0">
<tr>
<th>File ID</th>
<th>Generate Key</th>
</tr>
<%
Connection con = DbConnector.getConnection();
PreparedStatement pstm = null;
String sql = "select u.uniquserid, t.filename, t.status, t.cloud, t.date_, t.report, t.FileID from transaction t join user u on u.userid = t.user order by t.date_ desc;";
pstm = con.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
while (rs.next()) { %>
<tr>
<td><%=rs.getString(7)%></td>
<% if (rs.getString(3).contains("s")) {%>
<%request.getSession().setAttribute("PassFID", rs.getString(7));%>
<td><input type="button" value='Generate Key' onclick=""></input></td>
<%} else {%>
<td></td>
<%}%>
</tr>
<%}%>
</table>
Use jquery to do your task.
Change your html code to these lines of code.
<form method="post" action="#" name="Form" id="Form" >
<input type="button" value="one" id="One"/>
<input type="button" value="two" id="Two"/>
</form>
And add these lines in your script
$('input:button').click(function() {
alert($(this).val());
var value=$(this).val();
var url='hello?good=';
url+=value;
$("#Form").attr("action",url);
$("#Form").submit();
});
You can use jquery 1.7.1 and above. Hope this helps you. Happy Coding :)
I create this richiesta.html:
<HTML>
<BODY>
<table border> //create a simple table
<tr>
<td>
<form ACTION="richiesta.asp"> //open the file richiesta.asp
<table> //start a table format
<tr><td><input name="cognome" size="20"/></tr> //contain a input text
</table>
</form>
</td>
</tr>
<td><input type="submit" value="Invia"></td><td> // contein a button to send value to DB
</table>
</BODY>
</HTML>
I create richiesta.asp:
<HTML>
<BODY>
<%
cognome = Request.Form("cognome")
%>
<%
Session.timeout = 1 //Check the session
If IsObject(Session("iscrizioni")) Then
Set conn = Session("iscrizioni")
Else
Set conn = Server.CreateObject("ADODB.Connection") //Check the connection
conn.open "iscrizioni"
Set Session("iscrizioni") = conn
End If
%>
<%
If Stato = "" Then
SQL="INSERT INTO iscrizioni (Cognome) VALUES ("SQL=SQL & "'" & cognome & "', "SQL=SQL ")
response.write(SQL) //
conn.execute(SQL) // Insert value
conn.close //Close the connection
%>
//
// End Page
I want to insert in the BD Anagrafica, table Anagrafica the name of a student.
DB structure:
HTML Form action should be a valid (relative/absolute) url and not a physical location.
Also the input control and submit button should be inside form for default form submit.
Please change your <form> tags action attribute
<form action="riciesta.asp" >
<table>
<tr><td><input name="cognome" size="20"/></td></tr>
<tr><td><input type="submit" value="submit"/></td></tr>
</table>
</form>