how to execute java code from a jsp page using a button? - javascript

this is my jsp code:
EMAIL.JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Example</title>
</head>
<body>
<form method="post" action="">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2">Enter the information</th>
</tr>
</thead>
<tbody>
<tr>
<td>To Address</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>AttachFile</td>
<td<inputtype="text"value=".\ogc\hb1_800.jpg"id=".\ogc\hb1_800.jpg" />
</td>
</tr>
<tr>
<td><input type="reset" value="Clear" /></td>
<td><input type="Submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</center>
</form>
and on clicking the submit button i need to execute the java code:
final.java which is below:-
FINAL.JAVA
package com.grid;
public class final {
public static void main(String[] args) {
String ToAddress = new String[]{"8789951#gmail.com"};
String Subject = "Hi this is test Mail";
String AttachFile = {".\ogc\notepad\styles\thumbs\hb1_800.jpg"};
new Email().sendMail(ToAddress,Subject,AttachFile);
}
}
it calls the email.java
package com.grid;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Email{
private String SMTP_HOST = "smtp.gmail.com";
private String FROM_ADDRESS = "n123f#gmail.com";
private String PASSWORD = *****";
private String FROM_NAME = "Abc";
public boolean sendMail(String ToAddress,String Subject,String AttachFile) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.auth", "true");
props.put("mail.debug.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(props, new SocialAuth());
MimeMessage msg = new MimeMessage(session);
InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
msg.setFrom(from);
InternetAddress[] ToAddress = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
ToAddress = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, ToAddress);
msg.setSubject(Subject);
MimeBodyPart msgBodyPart = new MimeBodyPart();
// Fill the message
msgBodyPart.setText("This is message body");
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(msgBodyPart);
// Part two is attachment
if (FileName != null && FileName.length > 0)
{
for (String filePath : FileName)
{
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.AttachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
/*DataSource source = new FileDataSource(filename);
msgBodyPart.setDataHandler(new DataHandler(source));
msgBodyPart.setFileName(filename);
multipart.addBodyPart(msgBodyPart);*/
msg.setContent(multipart);
Transport.send(msg);
return true;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (MessagingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null,ex);
return false;
}
}
class SocialAuth extends Authenticator {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
}
}
}
Now my doubt is how to execute final.java (which is a running code) on clicking the button submit in email.jsp page?

Here is a simple servlet for demonstration:
JSP:
<form method="post" action="/email">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2">Enter the information</th>
</tr>
</thead>
<tbody>
<tr>
<td>To Address</td>
<td><input type="text" name="to" value="" /></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="subject" value="" /></td>
</tr>
<tr>
<td>AttachFile</td>
<td> <input type="text" name="file" value=".\ogc\hb1_800.jpg"id=".\ogc\hb1_800.jpg" />
</td>
</tr>
<tr>
<td><input type="reset" value="Clear" /></td>
<td><input type="Submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</center>
</form>
Servlet:
#WebServlet(name="mytest", urlPatterns={"/email"})
public class MailServlet extends javax.servlet.http.HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String file = request.getParameter("file");
new Email().sendMail(to,subject,file);
response.getWriter().println("Email sent");
}
}

Related

Thymeleaf form submit with ArrayList Object

I have written a simple program for form submit with the data(ArrayList) to send from table to controller class.
While submitting the form the data is always empty not sure what I am doing wrong here.
I am almost spending a lot of time to identify the issue no luck :(
Controller Class ( Where I always getting null in Post method )
public class AccountContoller {
private ArrayList<AccountwithSelection> allAccountwithSelect = new ArrayList<AccountwithSelection>();
public AccountContoller()
{
//Written some test data in Array
AccountwithSelection accountwithSelection1 = new AccountwithSelection();
accountwithSelection1.setAccountnumber("Acct1");
accountwithSelection1.setIlc("ILC1");
allAccountwithSelect.add(accountwithSelection1);
AccountwithSelection accountwithSelection2 = new AccountwithSelection();
accountwithSelection2.setAccountnumber("Acct2");
accountwithSelection1.setIlc("ILC2");
allAccountwithSelect.add(accountwithSelection2);
}
#RequestMapping(value = "/accountload", method = RequestMethod.GET)
String accountload(Model model) {
AccountSelectionListWrapper wrapper = new AccountSelectionListWrapper();
wrapper.setAccountList(allAccountwithSelect);
model.addAttribute("accountload", wrapper);
return "accountload";
}
#RequestMapping(value = "/accountload", method = RequestMethod.POST)
public String addimeiPost(Model model,
#ModelAttribute("accountload") AccountSelectionListWrapper wrapper,
HttpServletRequest request) {
System.out.println(wrapper.getAccountList()); //Always getting null, why ?
return "accountload";
}
}
Class: AccountwithSelection
public class AccountwithSelection {
public String accountnumber, ilc;
public String getAccountnumber() {
return accountnumber;
}
public void setAccountnumber(String accountnumber) {
this.accountnumber = accountnumber;
}
public String getIlc() {
return ilc;
}
public void setIlc(String ilc) {
this.ilc = ilc;
}
}
WrapperClass- AccountSelectionListWrapper
public class AccountSelectionListWrapper {
public ArrayList<AccountwithSelection> accountList;
public ArrayList<AccountwithSelection> getAccountList() {
return accountList;
}
public void setAccountList(ArrayList<AccountwithSelection> accountList) {
this.accountList = accountList;
}
}
HTML Form:(accountload.html)
<form action="#" th:action="accountload" th:object="${accountload}" method="post">
<div class="row">
<div class=form-group-1>
<input type="submit" value="Send Data" name="action">
</div>
</div>
<table id="mytable" class="table">
<tbody class="table-tbody" style="width: 90%">
<tr class="table-head">
<th>ACCOUNT NUMBER</th>
</tr>
<tr class="table-row">
<tr class="table-row" th:each="account, stat : *{accountList}">
<td class="table-data" th:text="${account.getAccountnumber()}"
th:field="*{accountList[__${stat.index}__].accountnumber}"
th:value="${account.getAccountnumber()}"></td>
</tr>
</tbody>
</table>
</form>
<td /> elements aren't submitted with a form. You need to use some kind of input. It should look something like this:
<td class="table-data">
<input type="text" th:field="*{accountList[__${stat.index}__].accountnumber}" />
</td>
or if you want to submit without seeing the fields as editable, something like this
<td class="table-data">
<span th:text="${account.accountnumber}" />
<input type="hidden" th:field="*{accountList[__${stat.index}__].accountnumber}" />
</td>

How to get the data from database into different textboxes on selecting a name in the textbox

I have a jsp page with different textboxes on entering the values in the textboxes and clicking "save" button it is saving into the database.I will post an image in order to understand what am i asking.
So the question is when i enter a name such as "Ferrari" the textbox of "Organisation Name" should scroll down giving the names starting like "Ferrari Constructions","Ferrari Resources","Ferrari Motors","Ferrari Racing".Now i will select a name like "Ferrari Motors" then it should fetch the data of "Ferrari Motors" and display the data into all other textboxes automatically in the sense like autofiling.
NOTE:No need to fill the tabular data automatically.Only Textboxes should be filled.I am posting the code below
Ihome.jsp
<script language="javascript">
// Add row to the HTML table
function generate(){
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
var f1 = document.form;
f1.setAttribute("target","_blank");
f1.method="post";
f1.action='Invoicedisplay.jsp?rowCount='+rowCount;
f1.submit();
}
function generate1(){
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
var f = document.form;
f.target="";
f.method="post";
f.action='addInvoice.jsp?rowCount='+rowCount;
// f.submit();
}
function generatePdf(){
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
var f = document.form;
f.method="post";
f.action='invoiceDisplayPdf.jsp?rowCount='+rowCount;
f.submit();
}
function generateWord(){
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
var f = document.form;
f.method="post";
f.action='invoice_display_word.jsp?rowCount='+rowCount;
f.submit();
}
</script>
<!-- <center> -->
<form name="form" action="Invoicedisplay.jsp" method="post">
<!-- <center> <input type="checkbox" value="yes" name="header"/> <b>Include Letter Head?</b></center> -->
<table>
<tr>
<td> </td>
<td>
<table width="900" border="0" cellpadding="0" cellspacing="8">
<tr>
<td width="134"><div align="center"><strong><u> BILLED TO</u></strong></div></td>
<td width="160"> </td>
<td width="15"> </td>
<td width="8"> </td>
<td width="8"> </td>
<td width="140"> </td>
<td width="149"><strong><u>TAX INVOICE</u> </strong></td>
<br/>
</tr>
<tr>
<td style="padding-left:50px;"><strong>OrganisationName</strong></td>
<td><input name="bname" type="text" id="bname" value="" /></td>
<td> </td>
<td> </td>
<td> </td>
<td ><strong>Invoice NO. </strong></td>
<td><input type="text" name="invNo" /></td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>
Delivery Address</strong></td>
<td><textarea name="bDelivAdd" cols="21" rows="3" id="bDelivAdd"></textarea></td>
<td> </td>
<td> </td>
<td> </td>
<td ><strong>InvoiceDate </strong></td>
<td>
<input type="text" id="invoiceDate" name="invoiceDate" class="search_textbx" readonly="readonly" placeholder="&nbsp &nbsp dd-mm-yyyy"/> </td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>PhoneNo.</strong></td>
<td><input name="bno" type="text" id="bno" value="" /></td>
<td> </td>
<td> </td>
<td> </td>
<td><strong>Buyer Order No. </strong></td>
<td><input type="text" name="buyerOrderNo" /></td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>PAN No.</strong></td>
<td><input type="text" name="bpan" /></td>
<td> </td>
<td> </td>
<td> </td>
<td><strong>Buyer Order Date </strong></td>
<td>
<input type="text" id="buyerorderDate" name="buyerorderDate" class="search_textbx" readonly="readonly" placeholder="&nbsp &nbsp dd-mm-yyyy"/> </td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>Attention</strong></td>
<td><input type="text" name="bAttn" /></td>
<td> </td>
<td> </td>
<td> </td>
<td><strong>Mode/Terms of Payment </strong></td>
<td><input type="text" name="termsOfPmnt" /></td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>Esugam No</strong></td>
<td><input type="text" name="esugamNo" /></td>
<td> </td>
<td> </td>
<td> </td>
<td><strong>Delivery Note </strong></td>
<td><input type="text" name="delivNote" /></td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>Dispatch Document No</strong></td>
<td><input type="text" name="dispDocNo" /></td>
<td> </td>
<td> </td>
<td> </td>
<td ><strong>Dispatch Through</strong></td>
<td><input type="text" name="dispThrough" /></td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>Dispatch Date </strong></td>
<td>
<input type="text" id="dispatchDate" name="dispatchDate" class="search_textbx" readonly="readonly" placeholder="&nbsp &nbsp dd-mm-yyyy"/></td>
<td> </td>
<td> </td>
<td> </td>
<td><strong>Destination </strong></td>
<td><input type="text" name="destination" /></td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>Terms of Delivery</strong></td>
<td><input type="text" name="termDelivery" /></td>
<td> </td>
<td> </td>
<td> </td>
<td><strong>Discount </strong></td>
<td><input type="text" name="discount" /></td>
</tr>
<tr>
<td style="padding-left:50px;"><strong>Buyer VAT/TIN</strong></td>
<td><input type="text" name="bTinNo" /></td>
<td> </td>
<td> </td>
<td> </td>
<td style="padding-right:10;"> <input type="checkbox" value="yes" name="cstCheck"/><b>Buyers CST No</b></td>
<td><input type="text" name="bcstNo" /></td>
</tr>
<!-- <tr> -->
<!-- <td style="padding-right:10;"> <input type="checkbox" value="yes" name="cstCheck"/><b>Buyers CST No</b></td> -->
<!-- <!-- <td><strong>Buyers CST No </strong></td> -->
<!-- <td><input type="text" name="cstNo" /></td> -->
<!-- </tr> -->
</table></td>
</tr>
</table>
<br/>
<center>
<div style="width:900px; height:230px; overflow:auto;">
<table id="my_table" align="center" border="2" cellpadding="0" cellspacing="0">
<thead><tr>
<th>Select</th>
<th>Sl.no</th>
<th>Description of Services/Goods</th>
<th>Quantity</th>
<th>Price/Unit</th>
<th>CST %</th>
<th>VAT5.5</th>
<th>VAT14.5</th>
<th>ServiceTax</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br>
</center>
<center>
<hr/>
<bgcolor ="red"/>
<input type="button" value="Add row" name="add" onClick="addRow()" />
<input type="button" value="Delete selected rows" name="delete_all" onClick="deleteSelectedRows()" />
<input type="button" value="Delete all rows" name="delete" onClick="deleteAllRows()" /><br/>
<hr/>
<p>
<strong>
<label for="servtax"></label>
</strong>
<input type="submit" value=" Save" onclick="generate1()" />
<input type="submit" value="View Invoice" onclick="generate()" />
<!-- <input type="submit" value="View Invoice in Pdf" onclick="generatePdf()" /> -->
</center>
<hr/>
</form>
addinvoice.jsp
<body>
<%
String organizationName, phoneNo, buyDate, invoiceNo, buyerOrderNo, esugamNo, deliveryAddress, PANNo, deliveryNote, invoiceDate, termsofPayment, dispatchDocumentNo, attention, dated, dispatchThrough, destination, termsOfDelivery, discount, buyerTin, buyerCSTNo;
int CId =0;
organizationName = request.getParameter("bname");
phoneNo = request.getParameter("bno");
buyDate = request.getParameter("buyerorderDate");
invoiceNo = request.getParameter("invNo");
buyerOrderNo = request.getParameter("buyerOrderNo");
esugamNo = request.getParameter("esugamNo");
PANNo = request.getParameter("bpan");
deliveryNote = request.getParameter("delivNote");
invoiceDate = request.getParameter("invoiceDate");
attention = request.getParameter("bAttn");
dated = request.getParameter("dispatchDate");
dispatchThrough = request.getParameter("dispThrough");
destination = request.getParameter("destination");
termsOfDelivery = request.getParameter("termDelivery");
discount = request.getParameter("discount");
buyerTin = request.getParameter("bTinNo");
buyerCSTNo = request.getParameter("bcstNo");
deliveryAddress = request.getParameter("bDelivAdd");
termsofPayment = request.getParameter("termsOfPmnt");
dispatchDocumentNo = request.getParameter("dispDocNo");
try{
DBConnect db =new DBConnect();
Connection con = db.getCon();
String sql ="insert into marketing_database.invoiceclient_details (OrganizationName,PhoneNo,BuyDate,InvoiceNo,BuyerOrderNo,EsugamNo,DeliveryAddress,PANNO,DeliveryNote,InvoiceDate,TermsOfPayment,DispatchDocumentNo,DispatchThrough,Destination,TermsofDelivery,Attention,Discount,BuyerTin,BuyerCSTNo,Dated) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
PreparedStatement ps =con.prepareStatement(sql);
ps.setString(1, organizationName);
ps.setString(2, phoneNo);
ps.setString(3, buyDate);
ps.setString(4, invoiceNo);
ps.setString(5, buyerOrderNo);
ps.setString(6, esugamNo);
ps.setString(7, deliveryAddress);
ps.setString(8, PANNo);
ps.setString(9, deliveryNote);
ps.setString(10, invoiceDate);
ps.setString(11, termsofPayment);
ps.setString(12, dispatchDocumentNo);
ps.setString(13, dispatchThrough);
ps.setString(14,destination );
ps.setString(15, termsOfDelivery);
ps.setString(16, attention);
ps.setString(17, discount);
ps.setString(18, buyerTin);
ps.setString(19, buyerCSTNo);
ps.setString(20, dated);
ps.executeUpdate();
//Get Max CID
String sql1 ="Select MAX(CId) from marketing_database.invoiceclient_details";
PreparedStatement ps1 = con.prepareStatement(sql1);
ResultSet rs =ps1.executeQuery(sql1);
while(rs.next())
{
CId =rs.getInt(1);
System.out.println("CId====="+CId);
}
con.close();
ps.close();
ps1.close();
rs.close();
System.out.println("Saved to Invoice Details");
}
catch(SQLException ex){
ex.printStackTrace();
}
//
String createdBy=(String)session.getAttribute("email");
String row = request.getParameter("rowCount");
System.out.println("Row Count====="+row);
int rowCount = Integer.parseInt(row);
String item,description;
String CST;
int quantity;
double perUnitPrice;
String serviceTax =null, vat5 = null, vat14 = null;
try{
DBConnect db =new DBConnect();
Connection con = db.getCon();
String sql = " select vat5,vat14,serviceTax FROM marketing_database.tax_info WHERE id='1' ;";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
vat5 = rs.getString("vat5");
vat14 = rs.getString("vat14");
serviceTax = rs.getString("serviceTax");
// CST = rs.getString("CST");
}
con.close();
ps.close();
rs.close();
}
catch(SQLException ex){
ex.printStackTrace();
}
int j=1;
List<Double> cstAmountList= new ArrayList<Double>();
List<Double> vat5AmountList= new ArrayList<Double>();
List<Double> vat14AmountList= new ArrayList<Double>();
List<Double> svcTaxAmountList= new ArrayList<Double>();
while (j < rowCount) {
float serviceTaxDB = 0, vat5DB = 0, vat14DB = 0;
description = request.getParameter("discription" + j);
if(request.getParameter("quantity" + j)==null ||request.getParameter("quantity" + j).equals(""))
{
quantity=0;
}
else{
quantity = Integer.parseInt(request.getParameter("quantity" + j));
}
if(request.getParameter("price"+ j)==null ||request.getParameter("price"+ j).equals(""))
{
perUnitPrice=0;
}
else{
perUnitPrice = Double.parseDouble(request.getParameter("price"+ j));
}
// quantity = Integer.parseInt(request
// .getParameter("quantity" + j));
// perUnitPrice = Double.parseDouble(request.getParameter("price"+ j));
double totalPrice = (quantity*perUnitPrice);
CST =request.getParameter("CST"+ j);
float cst;
if(CST==null ||CST=="")
{
cst=0;
}
else{
cst=Float.parseFloat(CST);
}
double cstAmnt=0,vat5Amnt=0,vat14Amnt=0,serviceTaxAmnt=0;
cstAmnt = (totalPrice*cst)/100;
//rounding to two decimal places
DecimalFormat cstroundoff = new DecimalFormat("0.00");
String cstround = cstroundoff.format(cstAmnt);
double cstroundofff = Double.parseDouble(cstround);
cstAmountList.add(cstroundofff);
String[] tax;
int length;
tax = request.getParameterValues("tax" + j);
if(tax==null ||tax.equals(""))
{
length=0;
}
else{
length = tax.length;
}
// String[] tax;
// tax = request.getParameterValues("tax" + j);
// int length = tax.length;
System.out.println("length===="+length);
if (tax != null) {
for (int k = 0; k < tax.length; k++) {
if (tax[k].contains("vat5")) {
vat5DB = Float.parseFloat(vat5);
vat5Amnt = (totalPrice*vat5DB)/100;
// rounding to two decimal places
DecimalFormat vat5roundoff = new DecimalFormat("0.00");
String vat5round = vat5roundoff.format(vat5Amnt);
double vat5roundofff = Double.parseDouble(vat5round);
vat5AmountList.add(vat5roundofff);
}
if (tax[k].contains("vat14")) {
vat14DB =Float.parseFloat(vat14) ;
vat14Amnt = (totalPrice*vat14DB)/100;
//rounding to two decimal places
DecimalFormat vat14roundoff = new DecimalFormat("0.00");
String vat14round = vat14roundoff.format(vat14Amnt);
double vat14roundofff = Double.parseDouble(vat14round);
vat14AmountList.add(vat14roundofff);
}
if (tax[k].contains("serviceTax")) {
serviceTaxDB = Float.parseFloat(serviceTax);
serviceTaxAmnt = (totalPrice*serviceTaxDB)/100;
//rounding to two decimal places
DecimalFormat svcroundoff = new DecimalFormat("0.00");
String svcround = svcroundoff.format(serviceTaxAmnt);
double svcroundofff = Double.parseDouble(svcround);
svcTaxAmountList.add(svcroundofff);
}
// if (tax[k].contains("cst")) {
// CSTDB =Float.parseFloat(CST);
// }
}
}
try{
DBConnect db =new DBConnect();
Connection con = db.getCon();
String sql ="INSERT INTO marketing_database.invoice (CId,CreatedBy,DescriptionOfGoods,Quantity,PerUnitPrice,VAT5,VAT14,ServiceTax,CST,TotalPrice) values (?,?,?,?,?,?,?,?,?,?);";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, CId);
ps.setString(2, createdBy);
ps.setString(3, description);
ps.setInt(4, quantity);
ps.setDouble(5, perUnitPrice);
ps.setDouble(6, vat5Amnt);
ps.setDouble(7, vat14Amnt);
ps.setDouble(8, serviceTaxAmnt);
ps.setDouble(9, cstAmnt);
ps.setDouble(10, totalPrice);
ps.executeUpdate();
System.out.println(" Saved to invoicing !!");
con.close();
ps.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
j = j + 1;
}
double subTotal =0.0;
double cstTotal =0.0;
double vat5Total= 0.0;
double vat14Total = 0.0;
double svcTaxTotal =0.0;
try{
DBConnect db =new DBConnect();
Connection con = db.getCon();
String sql = "select SUM(TotalPrice) FROM marketing_database.invoice WHERE CId='"+CId+"' ;";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
subTotal=rs.getDouble(1);
}
int cstSize = cstAmountList.size();
System.out.println("CST size==="+cstSize);
for(int i=0;i<cstSize;i++)
{
cstTotal+=cstAmountList.get(i);
}
int vat5Size =vat5AmountList.size();
System.out.println("vat5 size==="+vat5Size);
for(int i=0;i<vat5Size;i++)
{
vat5Total+=vat5AmountList.get(i);
}
int vat14size = vat14AmountList.size();
System.out.println("vat14 size==="+vat14size);
for(int i=0;i<vat14size;i++)
{
vat14Total+=vat14AmountList.get(i);
}
int svcSize = svcTaxAmountList.size();
for(int i=0;i<svcSize;i++)
{
svcTaxTotal+=svcTaxAmountList.get(i);
}
Double grandTotal =subTotal+cstTotal+vat5Total+vat14Total+svcTaxTotal;
int roundofff = (int) Math.round(grandTotal);
String sql1 = "UPDATE `marketing_database`.`invoiceclient_details` SET `SubTotal`=? ,`grandTotal`=? , `cstAmount`=? ,`vat5Amount`=? ,`vat14Amount`=?,`svcTaxAmount`=? WHERE `CId`='"+CId+"';" ;
PreparedStatement psmt = con.prepareStatement(sql1);
psmt.setDouble(1, subTotal);
psmt.setDouble(2, roundofff);
psmt.setDouble(3, cstTotal);
psmt.setDouble(4, vat5Total);
psmt.setDouble(5, vat14Total);
psmt.setDouble(6, svcTaxTotal);
psmt.executeUpdate();
con.close();
psmt.close();
System.out.println("Sub total updated in Invoice details");
}
catch(SQLException ex)
{
ex.printStackTrace();
}
response.sendRedirect("Ihome.jsp");
%>
</body>
you can use the jQuery for exchanging the data from the server on each event,
check the data for and bind it with your repective elements,
$.ajax({
type:'post', //you can use any method here
url:'serverpth',
data:{b: 'ok'}, //your data which you are looking for from database
}).success: function(data){
// bind your fields here with data
};

PhoneGap Calendar Plugin iOS non-responsive

<div class="jumbotron">
<h1>Set Up Appointment</h1>
<form action="" id="input" method="get" name="input">
document.addEventListener('deviceready', function(){ var cal; cal =
window.plugins.calendarPlugin; $('#submit').click(function() { function
createEvent(title,location,notes, startDate, endDate){ var title =
document.getElementById=("name"); var notes =
document.getElementById=("location"); var startDate =
document.getElementById=("startDate"); var endDate =
document.getElementById=("endDate");
cal.createEvent(title,location,notes,startDate,endDate); } }); },
false);<a href="https://www.nycm.com/Default.asp" target=
"blank"><img src=
"http://www.nycm.com/apcd/images/LogoTitle.gif"></a><br>
<div class="inputTable" style="width:300px">
<table>
<tr>
<td>Name</td>
<td><input id="name" type="text"></td>
</tr>
<tr>
<td>Location</td>
<td><input id="location" type="text"></td>
</tr>
<tr>
<td>Start Date</td>
<td><input id="startDate" type="date"></td>
</tr>
<tr>
<td>End Date</td>
<td><input id="endDate" type="date"></td>
</tr>
<tr>
<td>Additional Info</td>
<td><input id="notes" type="text"></td>
</tr>
</table>
<div class="submitButton">
<input id="submit" type="submit" value="Submit">
</div>
</div><br>
</form>
</div>
It takes in the input but it's not making an event in the native calendar on the phone.
I'm running it through the PhoneGap build on a mac using X code.
I really just need to know how to connect the javascript, using PhoneGap, to the native calendar on the iOS.
Any help would be awesome.
try this one.
make sure you already define your plugin in your config.xml
<feature name="CustomPlugin">
<param name="ios-package" value="CustomPlugin" />
</feature>
Implementing the plug-in by using Objective-C code
CustomPlugin.h
#import <Foundation/Foundation.h>
#import <Cordova/CDV.h>
#interface CustomPlugin : CDVPlugin
- (void)sayHello:(CDVInvokedUrlCommand*)command;
#end
CustomPlugin.m
#import "CustomPlugin.h"
#implementation CustomPlugin
- (void)sayHello:(CDVInvokedUrlCommand*)command{
NSString *responseString =
[NSString stringWithFormat:#"Hello World, %#", [command.arguments objectAtIndex:0]];
CDVPluginResult *pluginResult =
[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:responseString];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
#end
Calling a plug-in from JavaScript
function initial(){
var name = $("#NameInput").val();
cordova.exec(sayHelloSuccess, sayHelloFailure, "CustomPlugin", "sayHello", [name]);
}
function sayHelloSuccess(data){
alert("OK: " + data);
}
function sayHelloFailure(data){
alert("FAIL: " + data);
}

Javascript submit function returns Object is not a function error

Am using this function for the form submission just after one last check of 2 fields. But when submitting the form using javascript it returns the Object is not a function error. Didnt pasted the entire code of this page. pasted the required fields for this function. Any helps appreciated
<script type="text/javascript">
function validamt(strval){
var letters = /^[0-9]+(\.[0-9]{1,2})?$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function validno(strval){
var letters = /^\d+$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function finalcheck(){
var discount=$("#discount").val();
var stax=$("#stax").val();
var err=0;
if(discount!="In Rupees only" || stax!="(%)"){
if(!validno(stax)){err=1; alert('Invalid Service Tax');$("#stax").focus();}
if(!validamt(discount)){err=1;alert('Invalid Discount Amount');$("#discount").focus();}
}
alert(err);
if(err==0){
try{
document.getElementById('billsetupprocess').action="storebilling.php";
document.getElementById('billsetupprocess').submit();
}
catch(e){
alert(e);
}
}
}
</script>
<form name="billsetupprocess" id="billsetupprocess" method="post" action="storebilling.php" enctype="multipart/form-data" >
<table>
<tr>
<td>Discount</td>
<td><input name="discount" type="text" class="txtclass" id="discount" value="<?php if($discount!=""){echo $discount;} else {echo("In Rupees only");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='In Rupees only'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='In Rupees only';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/></td>
<td></td>
<td> </td>
</tr>
<tr>
<td>servicetax</td>
<td><input name="stax" type="text" class="txtclass" id="stax" value="<?php if($discount!=""){echo $servicetax;}else {echo("(%)");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='(%)'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='(%)';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/>
</td>
<td></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input name="submit" id="submit" type="button" value="Save Setup" onclick="finalcheck()" class="btnclass" /></td>
<td> </td>
<td> </td>
</tr>
</table>

"Undefined" when passing data to JavaScript from Android

I'm using this code but the value said "undefined" can anyone point me the problem?
this is my java class codes
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.frux.web.R.layout.activity_main);
String value = "Isiah";
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/www/index.html");
web.loadUrl("javascript:setValue(\""+ value +"\")");
}
and this is my webpage codes
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Whats your Name?
<input id="name" value="" />
<button onclick = "setValue()">Submit</button>
<script type="text/javascript">
function setValue(value){
var myValue = value;
document.getElementById("name").value = myValue;
}
</script>
</body>
</html>
I also try this one
web.loadUrl("javascript:setValue('"+ value +"')");
any thoughts will be highly appreciated
I used the codes in this HTML codes and its display nothing unlike the other codes above that I post.
<!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">
<script type="text/javascript">
function setValue(amount1)
{
myValue = amount1;
document.getElementById("amount").value = myValue;
}
function rand ( n )
{
document.getElementById("orderRefId").value = ( Math.floor ( Math.random ( ) * n + 1 ) );
}
</script>
</head>
<body onLoad="rand(200000);setValue();">
<!--
Note: https://www.pesopay.com/b2c2/eng/payment/payForm.jsp for live payment URL
https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp for test payment URL
-->
<form method="POST" name="frmPayment" action="https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp">
<table>
<tbody>
<tr>
<td>Order Reference No. (your reference number for every transaction that has transpired):</td>
<td><input type="text" id="orderRefId" name="orderRef" value="Test-001"/></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" name="amount" id="amount" value=""/></td>
</tr>
<tr>
<td>Currency Code - "608" for Philippine Peso, "840" for US Dollar:</td>
<td><input type="text" name="currCode" value="608"/></td>
</tr>
<tr>
<td>Language:</td>
<td><input type="text" name="lang" value="E"/></td>
</tr>
<tr>
<td>Merchant ID (the merchant identification number that was issued to you - merchant IDs between test account and live account are not the same):</td>
<td><input type="text" name="merchantId" value="18056869"/></td>
</tr>
<tr>
<td>Redirect to a URL upon failed transaction:</td>
<td><input type="text" name="failUrl" value="http://www.yahoo.com?flag=failed"/></td>
</tr>
<tr>
<td>Redirect to a URL upon successful transaction:</td>
<td><input type="text" name="successUrl" value="http://www.google.com?flag=success"/></td>
</tr>
<tr>
<td>Redirect to a URL upon canceled transaction:</td>
<td><input type="text" name="cancelUrl" value="http://www.altavista.com?flag=cancel"/></td>
</tr>
<tr>
<td>Type of payment (normal sales or authorized i.e. hold payment):</td>
<td><input type="text" name="payType" value="N"/></td>
</tr>
<tr>
<td>Payment Method - Change to "ALL" for all the activated payment methods in the account, Change to "BancNet" for BancNet debit card payments only, Change to "GCASH" for GCash mobile payments only, Change to "CC" for credit card payments only:</td>
<td><input type="text" name="payMethod" value="ALL"/></td>
</tr>
<tr>
<td>Remark:</td>
<td><input type="text" name="remark" value="Asiapay Test"/></td>
</tr>
<!--<tr>
<td>Redirect:</td>
<td><input type="text" name="redirect" value="1"/></td>
</tr>-->
<tr>
<td></td>
</tr>
<input type="submit" value="Submit">
</tbody>
</table>
</form>
</body>
</html>
Wrap your passed value in double quotes:
web.loadUrl("javascript:setValue(\""+value+"\")");
I got this! When you call loadUrl for the second time the page has not loaded yet. The solution would be attaching your setValue call to window.onload event:
super.loadUrl("javascript:window.onload = function(){setValue(\"haha\");};");
This code loads 'haha' into input correctly.
Try wrapping your value in a single quotes like so
web.loadUrl("javascript:setValue('"+ value +"')");
I had this issue when trying to access the DOM before it was ready. devmilles.com's solution worked but I spent a little more time experimenting.
Both of
webView.loadUrl("javascript:window.addEventListener('DOMContentLoaded',
function(){setValue('haha');}, false);");
webView.loadUrl("javascript:window.addEventListener('load',
function(){setValue('haha');}, false);");
worked for me, but attaching the event to document instead of window did not. DOMContentLoaded, where supported, responds slightly faster than load.
Additionally, it turns out that WebViewClient has always had an onPageFinished() event, which appears to work like the load event
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:setValue('haha');");
}
});
Lastly, I could emulate the behaviour with
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress == 100) {
view.loadUrl("javascript:setValue('haha');");
}
}
});
but I see no reason to use that over the WebViewClient approach (they may or may not be equivalent).
I am also facing same problem.But the issue is resolved using below way.
String testValue="abcdedfg";
String value = "\'"+testValue+"\'";
web.loadUrl("javascript:setValue(\""+value+"\")");

Categories

Resources