Download file from JSP with Javascript - javascript

The context: I have a JSP presenting an HTML page. Here I can choose files from a table (populated via MySQL). clicking on a row: the file is loaded from the DB (via MySQL query), then built via stream, then it should be downloaded. I'm able to build a file from a stream, but I can't enable the correct procedure for download it. The software is running on local, so there's no a client/server architecture (I'm aware Javascript is problematicfor this) I read many questions here about using Javascript, href links, jquery, but nothing seems to work.
Can someone provide a "classic example" or proper implementation for this? Sorry if my description is a little vague, I'll provide further details if necessary. Have a look to my jsp (Please ignore the code parts not related). Note: Some errors are due to uncoplete deleting of my efforts
`<%# page import="org.jdom2.Element"%>
<%# page
import="org.yawlfoundation.yawl.resourcing.rsInterface.WorkQueueGatewayClient"%>
<%# page import="org.jdom2.output.XMLOutputter"%>
<%# page import="org.jdom2.output.Format"%>
<%# page import="org.jdom2.input.SAXBuilder"%>
<%# page import="java.io.StringReader"%>
<%# page import="java.io.*"%>
<%# page import="java.sql.Connection"%>
<%# page import="java.sql.DriverManager"%>
<%# page import="java.sql.PreparedStatement"%>
<%# page import="java.sql.ResultSet"%>
<%# page import="java.sql.SQLException"%>
<%# page import="java.sql.Statement"%>
<%# page import="java.util.ArrayList"%>
<%# page import="java.util.List"%>
<%# page import="java.util.Map"%>
<%# page import="org.jdom2.Element"%>
<%# page import="org.yawlfoundation.yawl.elements.data.YParameter"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.Enumeration"%>
<%
String username = "";
String password = "password";
String columns = "columns";
String data1 = "<tr>";
String taskFlag = "void";
String clickedDOC = "";
String link = "";
String jDocTitle = "dummy jDocTitle";
String varName = "username";
String varName2 = "addDocument";
String varName3 = "addRequest";
String varName4 = "evaluateRequest";
String varName5 = "removeDocument";
String varName6 = "removeRequest";
String varName7 = "exit";
String wqURL = "http://localhost:8080/resourceService/workqueuegateway";
String error = "error";
boolean isModified = false;
boolean addDocument = false;
String redirectURL = (String) session.getAttribute("redirectURL");
if (redirectURL == null) {
redirectURL = request.getParameter("source");
session.setAttribute("redirectURL", redirectURL);
}
String submit = request.getParameter("submit");
System.out.println("submit: " + submit);
WorkQueueGatewayClient wqClient = new WorkQueueGatewayClient(wqURL);
String itemXML = (String) session.getAttribute("itemXML");
//if (itemXML == null) {
String itemid = request.getParameter("workitem");
String handle = request.getParameter("handle");
itemXML = wqClient.getWorkItem(itemid, handle);
session.setAttribute("itemXML", itemXML);
session.setAttribute("workitem", itemid);
session.setAttribute("handle", handle);
//}
if ((submit != null) && submit.equals("Add Document")) { // VALUTARE SE IL TASK TERMINA E VA RIAVVIATO (A TERMINE ADD) O SE RIMANE
ATTIVO (E DISPONIBILE DOPO ADD)
System.out.println("AddDocument clicked");
taskFlag = "addDocument";
addDocument = true;
isModified = true;
System.out.println("isModified: " + isModified);
/* session.removeAttribute("itemXML");
session.removeAttribute("workitem");
session.removeAttribute("handle");
session.removeAttribute("redirectURL"); */
redirectURL += "?complete=true";
response.sendRedirect(response.encodeURL(redirectURL));
return;
}
Element wir = new SAXBuilder().build(new StringReader(itemXML)).getRootElement();
Element updatedData = wir.getChild("updateddata");
Element data = (updatedData.getContentSize() > 0) ? updatedData : wir.getChild("data");
Element wirData = data.getChildren().get(0);
System.out.println("itemXML: " + itemXML);
if (!wqClient.successful(itemXML)) {
error = itemXML;
System.out.println("incipit error itemXML: " + itemXML);
} else { // wqClient.successful(itemXML)
if (wir != null) { //NIENTE DA INSERIRE NELL' IF
if (wirData != null) {
Element usernameXML = wirData.getChild(varName);
//Element taskFlagXML = wirData.getChild("taskFlag");
Element addDocumentXML = wirData.getChild("addDocument");
//addDocumentXML.removeContent();
// System.out.println("addDocumentXML: " + addDocumentXML.getText());
/*Element addRequestXML = null;
Element evaluateRequestXML = null;
Element removeDocumentXML = null;
Element removeRequestXML = null;
Element exitXML = null; */
if (usernameXML != null) {
username = usernameXML.getText();
//addDocument.removeContent();
//taskFlagXML.setText(taskFlag);
addDocumentXML.setText("true");
itemid = (String) session.getAttribute("workitem");
handle = (String) session.getAttribute("handle");
String dataString = new XMLOutputter(Format.getCompactFormat()).outputString(wirData);
String result = wqClient.updateWorkItemData(itemid, dataString, handle);
System.out.println("itemXML2: " + itemXML);
if (wqClient.successful(result) && isModified) { // QUI OPZIONE COMPLETAMENTO VALIDO
System.out.println("isModified 3: " + isModified);
/* session.removeAttribute("itemXML");
session.removeAttribute("workitem");
session.removeAttribute("handle");
session.removeAttribute("redirectURL"); */
redirectURL += "?complete=true";
response.sendRedirect(response.encodeURL(redirectURL));
} else { // wqClient.successful(result))
error = result;
System.out.println("not wqClient.successful(result): " + error);
}
} else { //dataitem != null && dataitem2 != null
error = "dataitems null";
System.out.println(error);
System.out.println("itemXML: " + itemXML);
System.out.println("inputs: " + username + " , " + password);
System.out.println("wirdata: " + wirData);
}
} else {//wirData
error = "This workitem does not contain any data for updating.";
System.out.println(error);
}
} else {
System.out.println("inputs null: ");
}
}
System.out.println("SQL start");
String queryAllDocuments = "SELECT title, file FROM appuser, document WHERE appuser.username = '" + username
+ "' AND appuser.role = document.applicantRole";
String queryAllRequests = "SELECT * FROM request WHERE request.applicantUsername = '" + username +"'";
String queryPendingRequests = "SELECT * FROM request WHERE request.applicantUsername = '" + username
+ "' AND request.status = 'pending' ";
String queryAllEvaluatingRequests = "SELECT * FROM request WHERE request.evaluetorUsername = '" + username+"'";
String queryEvaluatingPendingRequests = "SELECT * FROM request WHERE request.evaluetorUsername = '"
+ username + "' AND request.status = 'pending' ";
String queryGetDoc = "SELECT file FROM document WHERE document.title =";
Class.forName("com.mysql.jdbc.Driver");
Connection connection1 = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false",
"root", "root");
Statement statement1 = connection1.createStatement();
ResultSet resultSet1;
resultSet1 = statement1.executeQuery(queryAllDocuments);
System.out.println("resultSet1: "+resultSet1.first());
ResultSet resultSet2;
Statement statement2 = connection1.createStatement();
ResultSetMetaData rsmd;
rsmd = resultSet1.getMetaData();
System.out.println("rsmd: "+rsmd.getColumnCount());
int columnCount = rsmd.getColumnCount();
int index = 1;
int titleIndex = 1; // unica colonna doc
boolean flag = false;
while(flag){
jDocTitle = String.valueOf(request.getAttribute("docTitle")); // click su docTitle
if(jDocTitle.equals(null) ){
System.out.println("jDocTitle: "+jDocTitle);
queryGetDoc+= "'"+jDocTitle+"'";
resultSet2 = statement2.executeQuery(queryGetDoc);
System.out.println("resultSet2: "+resultSet2.first());
if(resultSet2!=null || !resultSet2.first()){
//resultSet2.first();
//costruisci file da query
System.out.println("jDocTitle1: "+jDocTitle);
File file = new File(jDocTitle);
file.createNewFile();
FileOutputStream fop = new FileOutputStream(file);
InputStream is = resultSet2.getBinaryStream(1);
byte[] buffer = new byte[1024];
int len;
for (int i = is.read(); i != -1; i = is.read()) {
fop.write(i);
}
is.close();
fop.close();
}
}else{
jDocTitle = "dummy docTitle";
System.out.println("docTitle null");
}
flag = false;
}
// <html xmlns="http://www.w3.org/1999/xhtml">
%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
function downloadFunction(){
var doc = document.getElementById("availableDocument").value;
doc = window.location= file;
alert(doc);
var xhttp = new XMLHttpRequest();
if(!doc){
doc = "no doc clicked";
}else
{
document.getElementById(doc).innerHTML = this.responseText;
xhttp.send();
}
flag = true;
}
</script>
<form name="userDataForm" method="post" action="" >
<h1>Welcome User</h1>
<h3> </h3>
<h3> </h3>
<h3>Available Documents</h3>
<table id= "docTable" style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<%
for (int i = 1; i < columnCount; i++) {
System.out.println(rsmd.getColumnName(i));
%><td><b>
<%=rsmd.getColumnName(i)%>
</b></td>
<% }%>
</tr>
<%
int i = 1;
resultSet1.first();
while (!resultSet1.isAfterLast()) {
for (; i != columnCount; i++) {
%>
<tr id="<%resultSet1.getString(i);%>">
<td>
<a id="availableDocument" href="#"; onclick=downloadFunction('<%=resultSet1.getString(i)%>')><%=resultSet1.getString(i)%></a>
</td>
<% }
if ( i % columnCount == 0)out.println("</tr><tr>");%>
<%resultSet1.next();}%>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<h3> </h3>
<h3>Submitted Requests</h3>
<table style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<td> </td>
<td style="width: 20px;"> </td>
</tr>
</tbody>
</table>
<p> </p>
<h3> </h3>
<h3> </h3>
<h3>Received Requests</h3>
<table style="height: 21px; float: left;" width="380">
<tbody>
<tr>
<td> </td>
<td style="width: 20px;"> </td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Add Document" /> <input
type="submit" name="submit" value="Add Request" />
</form>
</body>
</html>`

Related

Character encoding issue in Java/JS with the 'é' character in a field

The database (Postgresql) has a table with a column called
streetaddress1 (varchar(50)) in which the entry is 'Amelié'
The UI (React/JS) :
var streetAddress1 = event.target[1].value;
if (valProductDescription && valModelNumber && valAssemblyNumber && valName) {
url = url + "&streetAddress=" + streetAddress1 + " " + streetAddress2;
<div>
<Modal
isOpen={openCfcOverlay}
style={customStyles}
contentLabel="modal"
<div>
<Input
errorMessage='Please enter a valid Street Address'
error={cfcDeclaration.companyAddress1Error}
title="Street Address"
type="text"
name="Street Address"
value={typeof selectedCompany == 'undefined' ? "" : selectedCompany.streetAddress1}
disabled='edit'
/>
Then in the index.template.html file, I tried both
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="utf-8">
and
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="utf-16">
In the back-end (JAVA):
public CompanyRequest(JSONObject jsonObject)
this.streetAddress1 = (String) jsonObject.get("streetAddress1");
this.streetAddress2 = (String) jsonObject.get("streetAddress2");
This 'Street Address' field will appear in a pop-up that allows a pdf download. In here, the name 'Amelié' will appear as
public void generatePdf(String filePath, List<CfcRequest> cfcRequestList, String companyName, String streetAddress) throws IOException {
Document document = new Document(PageSize.A4, 36, 36, 36, 72);
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
if (image != null) {
Image img = Image.getInstance(image, null);
img.setAbsolutePosition(36f, 775f);
img.scaleToFit(150, 40);
document.add(img);
}
String modifiedRegionAddress = "";
String country = "";
boolean zipcodeAdded = false;
String[] address = regionAddress.split(" ");
for (int i = 0; i < address.length; i ++) {
if (!zipcodeAdded) {
try {
Integer.parseInt(address[i]);
zipcodeAdded = true;
} catch(NumberFormatException e) {}
modifiedRegionAddress += address[i] + " ";
} else {
country += address[i] + " ";
}
}
Paragraph header = new Paragraph("PDF Download", headerFont);
header.setAlignment(Element.ALIGN_CENTER);
header.setSpacingAfter(20);
document.add(header);
// Date and additional stuff
DateFormat df = new SimpleDateFormat("MM/dd/yy");
Date dateobj = new Date();
PdfPTable basicInfoTable = new PdfPTable(new float[]{3, 2});
PdfPCell dateTitleCell = new PdfPCell(new Paragraph("Date Issued:", tableHeaderFont));
PdfPCell dateCell = new PdfPCell(new Paragraph(df.format(dateobj), titleFont));
PdfPCell authorizedCell = new PdfPCell(new Paragraph("Authorized Signature:", tableHeaderFont));
PdfPCell companyNameCell = new PdfPCell(new Paragraph(companyName, titleFont));
PdfPCell streetAddressCell = new PdfPCell(new Paragraph(streetAddress, titleFont));
PdfPCell regionAddressCell = new PdfPCell(new Paragraph(modifiedRegionAddress, titleFont));
PdfPCell countryAddressCell = new PdfPCell(new Paragraph(country, titleFont));
PdfPCell emptyCell = new PdfPCell();
emptyCell.setBorder(Rectangle.NO_BORDER);
dateTitleCell.setBorder(Rectangle.NO_BORDER);
dateCell.setBorder(Rectangle.NO_BORDER);
authorizedCell.setBorder(Rectangle.NO_BORDER);
companyNameCell.setBorder(Rectangle.NO_BORDER);
streetAddressCell.setBorder(Rectangle.NO_BORDER);
regionAddressCell.setBorder(Rectangle.NO_BORDER);
countryAddressCell.setBorder(Rectangle.NO_BORDER);
basicInfoTable.addCell(dateTitleCell);
basicInfoTable.addCell(authorizedCell);
basicInfoTable.addCell(dateCell);
basicInfoTable.addCell(emptyCell);
basicInfoTable.addCell(companyNameCell);
basicInfoTable.addCell(emptyCell);
basicInfoTable.addCell(streetAddressCell);
basicInfoTable.addCell(emptyCell);
basicInfoTable.addCell(regionAddressCell);
basicInfoTable.addCell(emptyCell);
basicInfoTable.addCell(countryAddressCell);
basicInfoTable.addCell(emptyCell);
document.add(bodyTop);
document.add(reachTable);
document.add(bodyBottom);
final int FIRST_ROW = 0;
final int LAST_ROW = -1;
//Table must have absolute width set.
if (basicInfoTable.getTotalWidth() == 0)
basicInfoTable.setTotalWidth((document.right() - document.left()) * basicInfoTable.getWidthPercentage() / 100f);
basicInfoTable.writeSelectedRows(FIRST_ROW, LAST_ROW, document.left(), document.bottom() + basicInfoTable.getTotalHeight(), writer.getDirectContent());
document.close();
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Is this a utf-8/utf-16 problem? Why does the "é" character show up incorrectly in the field from the last picture? How do I fix this? and is it a back-end change or a UI change ?
The default encoding of the template databases in PostgreSQL is set to SQL_ASCII.Before retrieving that information did you change it to utf8 ?

compare the values of two text boxes and validate them in a session in asp.net

I code to generate captcha at page load. Here is the code.
protected void Page_Load(object sender, EventArgs e)
{
Bitmap objBMP = new System.Drawing.Bitmap(60, 20);
Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Green);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
Font objFont = new Font("Arial", 10, FontStyle.Italic);
string randomStr = "";
int[] myIntArray = new int[5];
int x;
Random autoRand = new Random();
for (x = 0; x < 5; x++)
{
myIntArray[x] = System.Convert.ToInt32(autoRand.Next(0, 9));
randomStr += (myIntArray[x].ToString());
}
Session.Add("randomStr", randomStr);
objGraphics.RotateTransform(-7F);
objGraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3);
Response.ContentType = "image/Gif";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
Now I want to validate between inputed value and generated captcha. Just like as
if (Page.IsValid && (txtInput.Text.ToString() == Session["randomStr"].ToString()))
Here I have saved query.of user using four text boxes.
public static string SaveEnquiry(string name, string email, string contact, string comments, string Company, string items, string ip,string captcha)
{
string StrReturn = "";
try
{
UserContactUs objUserContactUs = new UserContactUs();
string userCmt = "User Comment:" + comments; ;
int result = objUserContactUs.insertContactUs(name, contact, email, userCmt, GetUser_IP());
if (result > 0)
{
string mesageRec = name + " has enquired for " + ". Contact : " + contact + ", Email: " + email+ ". His Cmt: " + comments ;
//SendSMSToAdmin(mesageRec);
//SendSMSToUser(contact.TrimStart('0'));
StrReturn = "1#Thanks, for your interest.We will get back to you soon";
}
else
{
StrReturn = "0#Your enquiry is not saved. Please try Again!";
}
}
catch (Exception ex)
{
StrReturn = "0#" + ex.Message;
}
return StrReturn;
}
Now I want is if both the fields(i.e captcha image and inputtext box) are not equal then refresh the captcha image by showing a message invalid captcha.
Here is my contact form.
<div class="col-sm-2">
<img height="50" id="EnquiryCaptcha" alt="" style="border:inset;" src="InsertEnquiry.aspx" width="130">
</div>
<div class="col-sm-15">
<input type="text" name="txtInput" id="txtInput" placeholder="Captcha*" style="margin-top:auto; border:groove;">
</div>
<!--end-->
<button class="border-button " data-animation="fadeInUp" data-animation-delay="1000" type="button" id="btnsubmit" onclick="InsertEnquiry('contactForm')" name="submit">Send Message</button>

Javascript drop down menu and validate calendar picker

Ok I have a drop down menu that is dynamically generated by .jsp and populated with data fetched from database.2 dropdown list and 2 datepicker
The problem that I am having is with a JS validation, am not so good with JavaScript but for the purposes of my mini project I have to work with it anyway....
The problem is that with JS I am checking if a user has selected two drop-down fields and two date pickers so the form can be submitted and the list of the searching should be shows below the button else display a warning message indicating that the drop-downs and date pickers have not been filled.
Where should I do the validation of those 4 fields? How to use the'EXECUTE' to call the class from 'SelectOperation.java'(as per attached).
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import entityBeans.AccessLevel;
import entityBeans.Business;
import entityBeans.CustomerBranch;
import entityBeans.Menu;
import entityBeans.TransactionLog;
import entityBeans.User;
import cmnUtilities.CmnConstants;
public class SelectOperation {
Session session = ConnectionMySQL.getInstance().getConnection();
private static SelectOperation selectData = new SelectOperation();
private SelectOperation()
{
}
public User Select_login_User(String user_id)
{
User loginUser = null;
try
{
loginUser = (User)session.get(User.class,user_id.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return loginUser;
}
public User Chech_User_existence(String user_id)
{
User CheckUser = null;
try
{
CheckUser = (User)session.get(User.class,user_id.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return CheckUser;
}
public List<List<Menu>> Select_User_Menu(int Access_id)
{
List<Menu> UserMenu = null;
List<List<Menu>> Menus = new ArrayList<List<Menu>>();
AccessLevel acl = null ;
try
{
if(session.isOpen())
{
// acl = (AccessLevel)session.get(AccessLevel.class,Access_id.trim());
// StringBuffer AccessLevel = formatedMenuIds(acl.getMenuId());
// System.out.println(AccessLevel);
//UserMenu = (List<Menu>)session.createQuery("from Menu where menuId in ("+menuIds+")").list();
UserMenu = (List<Menu>)session.createQuery("from Menu where menuAccLevel >='"+Access_id+"'").list();
List<Menu> MainModule = new ArrayList<Menu>();
List<Menu> SubModule = new ArrayList<Menu>();
for(Menu seperateMenu : UserMenu)
{
if((seperateMenu.getMenuId().length()) == CmnConstants.MAIN_MENU)
{
MainModule.add(seperateMenu);
}
if((seperateMenu.getMenuId().length()) == CmnConstants.SUB_MENU)
{
SubModule.add(seperateMenu);
}
}
for(Menu disp1 : MainModule)
{
List<Menu> finaly = new ArrayList<Menu>();
finaly.add(disp1);
for(Menu disp2 : SubModule)
{
if(disp2.getMenuId().startsWith(disp1.getMenuId()))
{
finaly.add(disp2);
}
}
Menus.add(finaly);
}
System.out.println(Menus);
}
else
{
System.out.println("session closed");
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
return Menus;
}
//METHOD RETURNS ALL ACCESS LEVEL CODE AND IT'S DESCRIPTION
public List<AccessLevel> getAllAccessLevel()
{
List<AccessLevel> accessList = null;
try
{
accessList = (List<AccessLevel>)session.createQuery("from AccessLevel").list();
System.out.println(accessList);
}
catch(Exception exception)
{
exception.printStackTrace();
}
return accessList;
}
//METHOD TO SELECT ALL BRANCH IDS
public List<CustomerBranch> getAllCustomerBranch()
{
List<CustomerBranch> branchList = null;
try
{
branchList = (List<CustomerBranch>)session.createQuery("from CustomerBranch").list();
System.out.println(branchList);
}
catch(Exception exception)
{
exception.printStackTrace();
}
return branchList;
}
//METHOD TO SELECT ALL TRANSACTION_LOG DETAILS
public List<TransactionLog> getAllTransactionLog()
{
List<TransactionLog> TxnList = null;
try
{
TxnList = (List<TransactionLog>)session.createQuery("from TransactionLog").list();
System.out.println(TxnList);
}
catch(Exception exception)
{
exception.printStackTrace();
}
return TxnList;
}
//METHOD TO SELECT ALL BUSINESS
public List<Business> getAllBusiness()
{
List<Business> BusinessList = null;
try
{
BusinessList = (List<Business>)session.createQuery("from Business").list();
System.out.println(BusinessList);
}
catch(Exception exception)
{
exception.printStackTrace();
}
return BusinessList;
}
public Business SelectBusiness_Id(String business_id)
{
Business CheckBusiness_id = null;
try
{
CheckBusiness_id = (Business)session.get(Business.class,business_id.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return CheckBusiness_id;
}
public CustomerBranch SelectBranch_Id(String branch_id)
{
CustomerBranch CheckBranch_id = null;
try
{
CheckBranch_id = (CustomerBranch)session.get(CustomerBranch.class,branch_id.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return CheckBranch_id;
}
public TransactionLog FromDateSel(String txn_date)
{
TransactionLog transDateFrom = null;
try
{
transDateFrom = (TransactionLog)session.get(TransactionLog.class,txn_date.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return transDateFrom;
}
public TransactionLog ToDateSel(String txn_date)
{
TransactionLog transDateTo = null;
try
{
transDateTo = (TransactionLog)session.get(TransactionLog.class,txn_date.trim());
}
catch(Exception exception)
{
exception.printStackTrace();
}
return transDateTo;
}
// Will returns all menu ids
/*public StringBuffer formatedMenuIds(String text)
{
String[] val = text.split(",");
StringBuffer sb = new StringBuffer();
for(String cc :val)
{
sb.append("'"+cc+"'"+",");
}
if(sb.toString().endsWith(","))
{
sb.delete(sb.length()-1, sb.length());
}
return sb;
}*/
public static SelectOperation getInstance()
{
return selectData;
}
}
I think i just need so more javascript to do this i just dont know how. Thanks for your help in advance.
<% #page import = "allDatabaseOperations.SelectOperation" %>
<% #page import = "java.util.List" %>
<% #page import = "entityBeans.TransactionLog" %>
<% #page import = "entityBeans.Business" %>
<% #page import = "entityBeans.CustomerBranch" %>
<% #page language = "java"
contentType = "text/html; charset=ISO-8859-1"
pageEncoding = "ISO-8859-1" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< link rel = "stylesheet"
href = "../styles/style.css"
type = "text/css" / >
<%
List < TransactionLog > Allbranches = SelectOperation.getInstance().getAllTransactionLog();
List < Business > Businesslevel = SelectOperation.getInstance().getAllBusiness();
List < CustomerBranch > CustBranch = SelectOperation.getInstance().getAllCustomerBranch(); %>
< link rel = "stylesheet"
href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" >
< script src = "//code.jquery.com/jquery-1.10.2.js" > < /script>
<script src="/ / code.jquery.com / ui / 1.11.4 / jquery - ui.js "></script>
<link rel="
stylesheet " href=" / WebContent / styles / style.css ">
<script>
$(function() {
$( "#
fromdate " ).datepicker({
showOn: "
button ",
buttonImage: ".. / .. / images / calendar.png ",
buttonImageOnly: true,
buttonText: "
Select date "
});
});
$(function() {
$( "#
todate " ).datepicker({
showOn: "
button ",
buttonImage: ".. / .. / images / calendar.png ",
buttonImageOnly: true,
buttonText: "
Select date "
});
});
</script>
</head>
<body>
<form>
<table align="
center " style="
background - color: #F5D0A9;
padding: 70px;
border - top: 1px;
">
<tr>
<%-- added by Maihani on 181115(Wed) --%>
<td>
Business Id :-
</td>
<%--<td> <input type="
text " name="
BusinessId " size = "
46 "/> --%>
<td> <select name="
Business ">
<%for(Business business : Businesslevel) {%>
<option value=" <%= business.getBusinessId() %> "><%=business.getBusinessName()%></option>
<%}
%>
</select><%-- </td>--%>
</td>
</tr>
<td>
Branch Id :
</td>
<td>
<select name="
CustomerBranch ">
<%for(CustomerBranch custBranch : CustBranch) {%>
<option value=" <%= custBranch.getBranchId() %> "><%=custBranch.getBranchName()%></option>
<%}
%>
</select>
</td>
</tr>
<tr>
<td>
From Date :
</td>
<td>
<%-- <input type="
text " name="
BrachId " size = "
46 "/> --%>
<input type="
text " id="
fromdate ">
</td>
</tr>
<tr>
<td>
To Date :
</td>
<td>
<%--<input type="
text " name="
BrachId " size = "
46 "/> --%>
<input type="
text " id="
todate ">
</td>
</tr>
<tr>
<td>
</td>
<td align="
center "><input type="
submit " value="
Search Transaction "/></td>
</tr>
<tr >
<td colspan="
2 ">
<table align="
center ">
<tr bgcolor="
#333333">
<td><font color= "#FFFFFF" > User ID < /font></td >
< td > < font color = "#FFFFFF" > Branch ID < /font></td >
< td > < font color = "#FFFFFF" > Transaction Code < /font></td >
< td > < font color = "#FFFFFF" > Transaction Date < /font></td >
< td > < font color = "#FFFFFF" > Transaction Time < /font></td >
< /tr>
<%for(TransactionLog txn : Allbranches){%>
<tr bgcolor="#F2F2F2">
<td><%=txn.getUserId()%></td >
< td > <%= txn.getBranchId() %> < /td>
<td><%=txn.getTxnCode() %></td >
< td > <%= txn.getTxnDate() %> < /td>
<td><%=txn.getTxnTime() %></td >
< /tr>
<%} %>
</table >
< /td>
<td></td >
< /tr>
</table >
< /form>
</body >
< /html>
On the submit button, you can call a JavaScript function that in turn validates the values of your 4 input types and based on the validation result, you can continue with the form submit or show error message
<input type="submit" onclick="validateForm()" value="Search Transaction" />
<script>
function validateForm(){
var ip1 = $("#firstdropdownId").val();
var ip2 = $("#otherdropdownId").val();
var date1 = $("#firstdateId").val();
var date2 = $("#otherdateId").val();
if(ip1 == null || ip1.length.trim() == 0 || ip2 == null || ip2.length.trim() == 0 || idt1 == null || dt1.length.trim() == 0 || dt2 == null || dt2.length.trim() == 0){
$("#errorMessageDiv").show();
return false;
}
else{
$("#errorMessageDiv").hide();
return true;
}
}
</script>
Or if you want to validate from java end, you can make an ajax call by passing the parameters as the input values, which will return the validate status of your form.

Add row in html table dynamically

I want to add row dinamically in my html table , then save the new row in my database with servlet.
how can i get the row in my servlet .please help me
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>
</BODY>
Try this code
<%#page import="javax.xml.crypto.Data"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<%# page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%Connection con =null; %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
<%
//Connection con;
Statement s=null;
ResultSet rs=null;
String url = "";
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(url);
}
catch (ClassNotFoundException cnfex)
{
cnfex.printStackTrace();
}
String sql = "select * from tbPresicription";
try
{
s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs =s.executeQuery(sql);
while(rs.next())
{
// System.out.println("Name : "+rs.getString("PresicriptionIDP"));
}
System.out.println(" rs --> " + rs.first());
}
catch(Exception e)
{
System.out.println("Hello :"+e);
}
%>
<script src="js/jquery.js"></script>
<script type="text/javascript" language="javascript">
i=1;
a=1;
function addRow()
{
//Row Insert....
var table=document.getElementById("dataTable");
var row1=table.insertRow();
var row2=table.insertRow();
var row3=table.insertRow();
var row4=table.insertRow();
//Cell Insert Start
var cell1=row1.insertCell(0);
cell1.rowSpan="4";
cell1.innerHTML="";
cell1.align="center";
cell1.style.width = "30px";
cell1.innerHTML=i++;
//DropDownList
var cell1=row2.insertCell(0);
var abc=document.createElement("input");
abc.id="CompanyName"+a;
var Company=document.createElement("label");
Company.innerHTML =" Brand: ";
Company.style.width = "10px";
var Select = document.createElement('select');
var opt1 = document.createElement('option');
<% try
{
System.out.println(" rs --> click " + rs.first());
String IDP = null;
String Name=null;
%>
opt1.value="";
opt1.text="----Select Tablet----";
Select.appendChild(opt1);
<%
while (rs.next())
{
IDP = rs.getString("PresicriptionIDP")+":"+rs.getString("BrandName")+":"+rs.getString("Generic")+":"+rs.getString("Info")+":"+rs.getString("Dosage")+":"+rs.getString("Days")+":"+rs.getString("Qauntity")+":"+rs.getString("DosageInfo")+":"+rs.getString("TabletName")+":";
Name=rs.getString("TabletName");
// System.out.println("IDP :"+IDP+"Name is :"+Name);
%>
var opt2=document.createElement("option");
opt2.value="<%= IDP %>";
opt2.text="<%= Name %>";
Select.appendChild(opt2);
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
Select.name="opt"+a;
Select.required="required";
Select.id="opt"+a;
var optid = "opt"+a;
var id=Select.id;
Select.setAttribute('onChange',"javascript:SelectItem(this.value,id);");
Select.style.width = "150px";
Company.readOnly = 'readonly';
cell1.appendChild(Select);
cell1.appendChild(Company);
cell1.appendChild(abc);
//Days Detail
var cell3=row2.insertCell(1);
var Days=document.createElement("input");
var Days1=document.createElement("label");
Days.type = "text";
Days1.innerHTML ="Days: ";
Days.name = "Days"+a;
Days.id="Days"+a;
Days.style.width = "30px";
cell3.rowSpan="2";
cell3.style.width = "83px";
cell3.appendChild(Days1);
cell3.appendChild(Days);
//Generic Detail
var cell1=row3.insertCell(0);
var Generic=document.createElement("input");
var Generic1 = document.createElement("label");
Generic.type = "text";
Generic1.innerHTML = "Generic: ";
Generic.name = "Generic"+a;
Generic.id = "Generic"+a;
Generic.style.width = "357px";
Generic.readOnly = 'readonly';
cell1.appendChild(Generic1);
cell1.appendChild(Generic);
//Dose Deside
var cell2=row2.insertCell(1);
var Dosage=document.createElement("input");
var Dosage1 = document.createElement("label");
Dosage.type = "text";
Dosage1.innerHTML = "Dosage: ";
Dosage.name = "Dosage"+a;
Dosage.id = "Dosage"+a;
Dosage.style.width = "80px";
cell2.rowSpan = "2";
cell2.appendChild(Dosage1);
cell2.appendChild(Dosage);
//Medicine Info
var cell1=row4.insertCell(0);
var Info=document.createElement("input");
var Info1 = document.createElement("label");
Info.type = "text";
Info1.innerHTML = "Info: ";
Info.name = "Info"+a;
Info.id = "Info"+a;
Info.readOnly = 'readonly';
Info.style.width = "500px";
cell1.style.width = "400px";
cell1.appendChild(Info1);
cell1.appendChild(Info);
cell1.colSpan="2";
//Medicine Dose Info...
var cell2 = row4.insertCell(1);
var DosageInfo = document.createElement("input");
var DosageInfo1 = document.createElement("label");
DosageInfo.type = "text";
DosageInfo1.innerHTML = "DosageInfo: ";
DosageInfo.name = "DosageInfo"+a;
DosageInfo.id = "DosageInfo"+a;
DosageInfo.style.width = "170px";
DosageInfo.readOnly = 'readonly';
cell2.colSpan = "2";
cell2.appendChild(DosageInfo1);
cell2.appendChild(DosageInfo);
//Medicine Qauntity define..
var cell4=row2.insertCell(3);
var Qauntity = document.createElement("input");
var Qauntity1 = document.createElement("label");
Qauntity.type = "text";
Qauntity1.innerHTML = "Qauntity: ";
Qauntity.name = "Qauntity"+a;
Qauntity.id = "Qauntity"+a;
Qauntity.style.width = "30px";
cell4.appendChild(Qauntity1);
cell4.appendChild(Qauntity);
cell4.rowSpan="2";
a++;
}
function SelectItem(val,id)
{
//alert('val : '+val);
var id1=id.substring(3);
//alert('id1 : '+id1);
var aa=val.split(":");
document.getElementById("CompanyName"+id1).value=aa[1];
document.getElementById("Generic"+id1).value=aa[2];
document.getElementById("Info"+id1).value=aa[3];
document.getElementById("Dosage"+id1).value=aa[4];
document.getElementById("Days"+id1).value=aa[5];
document.getElementById("Qauntity"+id1).value=aa[6];
document.getElementById("DosageInfo"+id1).value=aa[7];
}
function removeRow()
{
document.getElementById("dataTable").deleteRow(this);
}
</script>
<script type="text/javascript">
function addData()
{
//alert('hii : '+a);
var i;
var ss=0;
for(i=1;i<a;i++)
{
// alert('Hiiii : '+i);
var TabletName1=document.getElementById("opt"+i).value;
var CompanyName=document.getElementById("CompanyName"+i).value;
var Generic=document.getElementById("Generic"+i).value;
var Info=document.getElementById("Info"+i).value;
var Dosage=document.getElementById("Dosage"+i).value;
var Days=document.getElementById("Days"+i).value;
var Qauntity=document.getElementById("Qauntity"+i).value;
var DosageInfo=document.getElementById("DosageInfo"+i).value;
ss = ss+TabletName1;
}
// alert('TabletName1='+ss);
window.location.replace("index.jsp?name="+ss);
<%
int i=0;
String a = null;
try
{
String name=request.getParameter("name");
System.out.println("Name :"+name);
String data[]=name.split(":");
int size=data.length;
int size1=(size-1)/2;
String BrandName[]=new String[size1];
String TabletName[]=new String[size1];
String Generic[]=new String[size1];
String info[]=new String[size1];
String dosage[]=new String[size1];
String days[]=new String[size1];
String Qty[]=new String[size1];
String DosageInfo[]=new String[size1];
String PresicriptionIDP[]=new String[size1];
int x=0;
for(i=0;i<size+2;i++)
{
PresicriptionIDP[x]=data[i];
i++;
//System.out.println("PresicriptionIDP : "+PresicriptionIDP[x]);
BrandName[x]=data[i];
i++;
//System.out.println("BrandName : "+BrandName[x]);
Generic[x]=data[i];
i++;
//System.out.println("Generic : "+Generic[x]);
info[x]=data[i];
i++;
//System.out.println("info : "+info[x]);
dosage[x]=data[i];
i++;
//System.out.println("dosage : "+dosage[x]);
days[x]=data[i];
i++;
//System.out.println("days : "+days[x]);
Qty[x]=data[i];
i++;
//System.out.println("Qty :"+Qty[x]);
DosageInfo[x]=data[i];
i++;
//System.out.println("DosageInfo : "+DosageInfo[x]);
TabletName[x]=data[i];
i++;
//System.out.println("TabletName : "+TabletName[x]);
System.out.println("\n Value of : "+i);
x++;
System.out.println("Value of X="+x);
for(int ss=0;ss<x;ss++)
{
String insertTableSQL = "INSERT INTO tbPrescriptionNew"
+ "(PresicriptionIDP, TabletName, BrandName, Generic,Info,Dosage,Days,Qauntity,DosageInfo) VALUES"
+ "(?,?,?,?,?,?,?,?,?)";
PreparedStatement preparedStatement = con.prepareStatement(insertTableSQL);
preparedStatement.setString(1, PresicriptionIDP[ss]);
System.out.println("\n PresicriptionIDP" +PresicriptionIDP[ss]);
preparedStatement.setString(2, TabletName[ss]);
System.out.println("\n TabletName=" +TabletName[ss]);
preparedStatement.setString(3, BrandName[ss]);
System.out.println("\n BrandName=" +BrandName[ss]);
preparedStatement.setString(4, Generic[ss]);
System.out.println("\n Generic=" +Generic[ss]);
preparedStatement.setString(5, info[ss]);
System.out.println("\n info=" +info[ss]);
preparedStatement.setString(6, dosage[ss]);
System.out.println("\n dosage=" +dosage[ss]);
preparedStatement.setString(7, days[ss]);
System.out.println("\n days=" +days[ss]);
preparedStatement.setString(8, Qty[ss]);
System.out.println("\n Qty=" +Qty[ss]);
preparedStatement.setString(9, DosageInfo[ss]);
System.out.println("\n DosageInfo=" +DosageInfo[ss]);
// execute insert SQL stetement
preparedStatement.executeUpdate();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
}
</script>
</head>
<body>
<center>
<input type="button" class="selectItem" onClick="addRow('dataTable')" value = "AddRow">
<input type='button' value='Delete' onclick="removeRow()"/>
</center>
<table id="dataTable" border="1" width="894px;" align="center">
</table>
<input type="button" onClick="addData()" value = "AddData">
</body>
</html>

How to access gridview cell value with javascript

I have a javascript function that I am trying to validate the inputs of a gridview. My problem is that I cannot get the value of the cell. Here is what I have:
function fcnCheck() {
var grid = document.getElementById("<%= GridViewProducts.ClientID %>");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length-1; i++) {
cellPivot = grid.rows[i].cells[0];
cellStatus = grid.rows[i].cells[1];
if (cellPivot == "Yes" and cellStatus == "") {
alert("You must select an answer for all columns if Pivot is yes")
return false;
}
}
}
}
This line does not work: cellPivot = grid.rows[i].cells[0];
Most likely you want (edit)
var theDropdown = grid.rows[i].cells[0].elements[0];
var selIndex = theDropdown.selectedIndex;
cellPivot = theDropdown.options[selIndex].value;
Another possibly easier or more reliable way to do this would be to tag the cells controls you want in some way and select them directly?
http://aspdotnetcodebook.blogspot.com/2010/01/how-to-get-cell-value-of-gridview-using.html#comment-form
Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var list = "";
$("#btnGet").click(function() {
$("#<%=GridView1.ClientID %> tr").each(function() {
//Skip first(header) row
if (!this.rowIndex) return;
var age = $(this).find("td:last").html();
list += age + "</br>";
});
$("#listAge").html(list)
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<input type="button" id="btnGet" value="Get Cell Value" />
<div id="listAge">
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Create Object of person class
Person personObject = new Person();
//Assign Person list to GridView
GridView1.DataSource = personObject.GetPersonList();
//Call Bindmethod of GridView
GridView1.DataBind();
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<Person> GetPersonList()
{
//Retrun List of Person
List<Person> list = new List<Person>()
{
new Person{ID=1,Name="Person1",Age=32},
new Person{ID=2,Name="Person2",Age=45},
new Person{ID=3,Name="Person3",Age=43},
new Person{ID=4,Name="Person4",Age=21},
new Person{ID=5,Name="Person5",Age=76},
new Person{ID=6,Name="Person6",Age=54},
};
return list;
}
}
<script language="javascript" type="text/javascript">
function Calculate()
<br/>
{
<br/>
var grid = document.getElementById("<%=GridID.ClientID%>");
<br/>
var sum = 0; <br/>
for (var i = 1; i < grid.rows.length; i++)<br/>
{ <br/>
var Cell = grid.rows[i].getElementsByTagName("input");
<br/>if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[4].value);} }
<br/>
document.getElementById("<%=TextBox1.ClientID%>").value = sum;
}
<br/>
</script>
------------------------------------------------------------------------
<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
<asp:TextBox ID="cridnvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="CalculateTax();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>
//your gridview id in my case my gridview is named dgd and the id comes from
// ClientID
var myGrid = document.getElementById("<%= dgd.ClientID %>");
var oRows = myGrid.rows;
var k;
for (k = 1; k < oRows.length; k++)
{
var currentRow = myGrid.rows[k];
//now you can see the 1st,2nd and 3trd column value
alert(currentRow.cells[1].innerHTML);
alert(currentRow.cells[2].innerHTML);
alert(currentRow.cells[3].innerHTML);
}
function rowWisegetcellvalueingridview() {
///concat string
var str1 = "";
var n = document.getElementById('hdnColumn').value;
///concat string
var grid = document.getElementById('GridView1');
var Inputs = grid.getElementsByTagName('input');
var Inputsa = grid.getElementsByTagName('a');
var Inputsspan = grid.getElementsByTagName('span');
var Input = Inputs.length;
var j = 0;
var p = 0;
var r = 0;
for (t = 0; t < grid.rows.length - 1; t++) {
var HdnID1 = Inputs[j].value;
var HdnID2 = Inputs[j + 1].value;
var HdnID3 = Inputs[j + 2].value;
var HdnID4 = Inputs[j + 3].value;
var HdnID5 = Inputsa[p].innerHTML;
var HdnID6 = Inputsa[p + 1].innerHTML;
var HdnID7 = Inputsspan[r].innerHTML;
var varConcat = "(" + HdnID1 + "," + HdnID2 + "," + HdnID3 + "," + HdnID4 + "," + HdnID5 + "," + HdnID6 + "," + HdnID7 + "),\n";
n = n.concat(varConcat);
j = j + 4;
p = p + 2;
r = r + 1;
}
return false;
}

Categories

Resources