Inserting dynamic table data to mysql in jsp - html

I have created html file to upload user data and images.It includes dynamic table where user can insert row by clicking add button and delete row by clicking on remove button.My form is working fine and I am able to upload file and data to database but unable to insert dynamic table data i.e I split form fields into to table
1) passengertable:- landmark, location, fromdate, todate, ccn, passenger_number are inserted.
2) passengerdetailtable :- pname,pemail,pnumber,passengerid(foriegnkey reference passengertable) :=this is dynamic table data
My problem is that only current input values of pname,pemail,pnumber is inserted to mysql but remaining dynamically created row data is not inserted...
html file
<div>
<form action="getPassengerDetail" method="post" enctype="multipart/form-data">
<div>
<label for="lname">LandMark: </label>
<input id="lname" type="text" name="landmark" placeholder="Enter LandMark">
<br>
</div>
<div>
<label for="location" >Vehicle Required From: <span><sup class="red-star">*</sup></span>
</label>
<input id="location" type="text" name="location" placeholder="Enter Location" required>
<input id ="fromdate" name ="fromdate" type="date" placeholder="From Date" required >
<input id="todate" name = "todate" type="date" placeholder="To Date" required>
<br>
<label for="id" id="checkboxlabel">multiple days</label>
<input type="checkbox" name="multiple_days" id="days" >
multiple days
<br>
</div>
<div>
<label for="ccn">Cost Center Number:</label>
<input id="ccn" type="text" name="cost_center_number" placeholder="Enter Cost Center Number">
<br>
</div>
<div>
<label for="pcount">Number Of Passenger:</label>
<input id="pcount" type="number" name="passenger_number" placeholder="Enter Passenger Count">
<br>
</div>
<div>
<label for="passenger_detail_table">Passenger Details :<span><sup class="red-star">*</sup>
</span></label>
<table id="passenger_detail_table" class="tablestyle">
<thead>
<tr valign="top" >
<td>
<label for="pname_" id="small-label">Name</label>
</td>
<td>
<label for="pemail_" id="small-label">E-mail</label>
</td>
<td>
<label for="pnumber_" id="small-label">Phone-Number</label>
</td>
<td>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input id="pname_" type="text" name="passenger_name[]" value=""
placeholder="Enter Name"onkeyup="this.value=this.value.replace(/[^a-z]/g,'');" class="alphaonly">
</td>
<td>
<input id="pemail_" type="email" name="passenger_email[]" value=""
placeholder="Enter E-mail" >
</td>
<td>
<input id="pnumber_" type="tel" name="passenger_phone_number[]" value=""
placeholder="Enter Phone-No" class="onlyphonenumber" >
</td>
<td>
<button type="button" id="addpassenger" name="passenger_add" style="background-
color:green;color:white;">Add</button>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<label for="crf_trf">CRF/TRF:</label>
<input id="crf_trf" name="crf_trf" type="file" multiple="multiple" value="Choose file">
<br>
</div>
<div>
<label for="ddetail">Duty Detail:</label>
<input id="ddetail" name=ddetail" type="text" width="100px" placeholder="Enter Duty
Detail">
<br>
</div>
<div>
<input type="submit" class="button" value="Submit" name="insert">
</div>
</form>
</div>
Jquery code
$(document).ready(function()
{
const maxCounter = 10;
let passengerCounter;
const $tb = $("#passenger_detail_table tbody ");
$('#addpassenger').on('click',function(e)
{
const pname = $.trim($("#pname_").val());
const pemail = $.trim($("#pemail_").val());
const pnumber = $.trim($("#pnumber_").val());
if(pname === "" || pemail === "" || pnumber === "")
{
alert("please enter the values...");
return;
}
passengerCounter = $tb.find("tr").length;
if (passengerCounter >= maxCounter)
{
alert("No more data to be placed")
return;
}
alert("The counter clicked."+passengerCounter);
const $firstRow = $tb.find(">:first-child");
let $newrowhtml = $firstRow.clone(true);
$firstRow.find(":input").val("");
$newrowhtml.find(":input")
.removeAttr("id","")
.attr('disabled', 'disabled');
$newrowhtml.find("[name=passenger_name]").val(pname);
$newrowhtml.find("[name=passenger_email]").val(pemail);
$newrowhtml.find("[name=passenger_phone_number]").val(pnumber);
$newrowhtml.find("[name=passenger_add]").replaceWith($('<button type="button"
style="background-color:red; color:white;" class="passenger_remove">Remove</button>'));
$("#passenger_detail_table").append($newrowhtml);
});
$("#passenger_detail_table").on('click', '.passenger_remove', function() {
$(this).closest("tr").remove();
});
servlet file: This servlet file act as controller for html function call to add details to database
#WebServlet("/getPassengerDetail")
#MultipartConfig(fileSizeThreshold=1024*1024*10,
maxFileSize=1024*1024*50,
maxRequestSize=1024*1024*100)
public class getPassengerDetailServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
String JDBC_Driver ="com.mysql.jdbc.Driver";
String URL ="jdbc:mysql://localhost/passengerdetail";
String username = "root";
String password = "root";
InputStream inputStream = null;
String landmark = request.getParameter("landmark");
String location = request.getParameter("location");
String fromdate = request.getParameter("fromdate");
String todate = request.getParameter("todate");
String ccn =request.getParameter("cost_center_number");
String pcount = request.getParameter("passenger_number");
String pname[] = request.getParameterValues("passenger_name[]");
String pemail[] = request.getParameterValues("passenger_email[]");
String pnumber[] =request.getParameterValues("passenger_phone_number[]");
String ddetail = request.getParameter("ddetail");
PrintWriter out = response.getWriter();
out.println(landmark+location+fromdate+todate+ccn+pcount);
// obtains the upload file part in this multipart request
Part crf_trf = request.getPart("crf_trf");
if (crf_trf != null)
{
inputStream = crf_trf.getInputStream();
}
out.println(crf_trf);
Class.forName(JDBC_Driver);
Connection con = DriverManager.getConnection(URL, username, password);
String query1 = "insert into passengertable
(landmarkname,location,fromdate,todate,ccn,pcount,crf_trf,dutydetail) values(?,?,?,?,?,?,?,?)";
PreparedStatement pstm = con.prepareStatement(query1,Statement.RETURN_GENERATED_KEYS);
pstm.setString(1, landmark);
pstm.setString(2, location);
pstm.setString(3, fromdate);
pstm.setString(4, todate);
pstm.setString(5, ccn);
pstm.setString(6, pcount);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
pstm.setBlob(7, inputStream);
}
pstm.setString(8, ddetail);
int row1=pstm.executeUpdate();
ResultSet rs = pstm.getGeneratedKeys();
int id=0;
while(rs.next())
{
id=rs.getInt(1);
}
String query2="insert into passengerdetailtable(pname,pemail,pnumber,passengerid)
values(?,?,?,?)";
int row2 = 0;
PreparedStatement pstmt;
for(int i=0;i<pname.length;i++)
{
pstmt = con.prepareStatement(query2);
pstmt.setString(1, pname[i]);
pstmt.setString(2, pemail[i]);
pstmt.setString(3, pnumber[i]);
pstmt.setInt(4, id);
row2=pstmt.executeUpdate();
}
if ((row1 > 0)&&(row2>0)) {
response.sendRedirect("Detail.jsp");
}
else{
response.sendRedirect("EntryForm.html");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Related

Why am i getting "undefined"

I dont understand why this is coming out as undefined
I have tried multiple ways of getting the values of each each variable and once i got the "value of null" error to go away, this is my issue.
<form class="" action="index.html" method="post">
Principal: <br>
<input type="text" name="principal" value="" id="prin"> <br>
Amount of Payments:<br>
<input type="text" name="payments" value="" id="payment"> <br>
Interest Rate: <br>
<input type="text" name="interest" value="" id="rate">
</form>
<br>
<button type="button" name="button" id="submit" onclick="interestTot()">Calculate</button>
<div id="div1">
</div>
</body>
</html>
let principal = document.querySelector("#principal");
let payment = document.querySelector("#payment");
let rate = document.querySelector("#rate");
let interest ;
if (document.querySelector("#principal)" != null) {
principal = parseInt(document.querySelector('#principal').value);
};
if (document.querySelector("#payment") != null) {
payment = parseInt(document.querySelector('#payment').value);
};
if (document.querySelector("#rate") != null) {
rate = parseInt(document.querySelector('#rate').value);
};
function interestTot() {
if (principal > 0) {
interest = rate / payment;
}
document.querySelector("#div1").innerHTML= interest
};

ASP Razor Web Pages - Form Submit is Moving My Data

When I submit my Login email (aka username), I want to keep it in my Login form.
When I submit my Register email (aka username), I want to keep it in my Register form.
What is happening is: when I submit my Login form, it writes the email (aka username) to the Register form. Please see image for what is happening.
#{
Page.Title = "Login";
var username = "";
var password = "";
var errorMessage = "";
var confirmPassword = "";
var regMsg = "";
var confToken = "";
var emailBody = "";
var minPass = 2;
var maxPass = 5;
if (!IsPost) {
if (WebSecurity.IsAuthenticated) {errorMessage = String.Format("You are already logged in. (Username: {0})", WebSecurity.CurrentUserName);}
}
if(WebSecurity.IsAuthenticated){
errorMessage = String.Format("You are already logged in. (Username: {0})", WebSecurity.CurrentUserName);
}
if(IsPost){
// Login Form
if (Request.Form["loginSub"] != null){
regMsg = "";
username = Request["username"];
password = Request["password"];
if(WebSecurity.Login(username,password,true)){
Response.Redirect("~/Profile");
}
else
{
errorMessage = "Invalid Username or Password. Please try again.";
}
}
// Register Form
if (Request.Form["registerSub"] != null){
WebSecurity.Logout();
errorMessage = "";
username = Request["username"];
password = Request["password"];
confirmPassword = Request["confirmPassword"];
try {
var mail = new System.Net.Mail.MailAddress(username);
} catch {
regMsg += "<br>Invalid email format.";
}
if (password != confirmPassword) {regMsg += "</br>Passwords don't match.";}
if (WebSecurity.UserExists(username)) {regMsg += String.Format("</br>User '{0}' already exists.", username);}
if (password.Length < minPass || password.Length > maxPass) {regMsg += "</br>Password doesn't meet length requirement.";}
if (regMsg == "") {
WebSecurity.CreateUserAndAccount(username,password,null,false); //Switch with "true" token
regMsg = String.Format("{0} created.", username);
Response.Write("<script>alert('Email verification sent! Please check your email to activate your account.');</script>");
//Response.Write("<script>location.href = 'Default.cshtml';</script>");
}
}
}
}
<style>header {visibility: hidden;}</style>
<body>
<h1>MySite</h1>
<p>
#if(errorMessage != ""){<span>#Html.Raw(errorMessage)</span>}
#if(regMsg != ""){<span>#Html.Raw(regMsg)</span>}
</p>
<fieldset class="fs100">
<legend>Login</legend>
<form method="post" name="login">
#if(WebSecurity.IsAuthenticated){
<p>You are currently logged in as #WebSecurity.CurrentUserName.
Log out
</p>
}
<p>
<label for="username">Email Address:</label><br/>
<input type="text" name="username" id="username" value="" />
</p>
<p>
<label for="password">Password:</label><br/>
<input type="password" name="password" id="password" value="" />
</p>
<p>
<input type="submit" name="loginSub" value="Submit" />
</p>
<p>Forgot Password?</p>
</form>
</fieldset>
<fieldset>
<legend>Register</legend>
<form method="post" name="register">
<p>
<label for="username">Email Address:</label><br/>
<input type="text" name="username" id="username" value='#Request["username"]' />
</p>
<p>
<label for="password">Password #minPass-#maxPass Characters:</label><br/>
<input type="password" name="password" id="password" value="" />
</p>
<p>
<label for="confirmPassword">Confirm Password:</label><br/>
<input type="password" name="confirmPassword" id="confirmPassword" value="" />
</p>
<p>
<input type="submit" name="registerSub" value="Register" />
</p>
</form>
</fieldset>
</body>
Your code is echoing the value from the request in the second form.
If you don't want it to do that, change your code to do something else.
You may want to change each form to have unique field names.

Correctly using gumbo-parser to iterate and find the things I need?

I'm working on a pure C99 practising project which can do a login simulation for our school's CAS login system.
Now I'm trying to use Gumbo HTML parser to parse our school's login page. Here is the form section and I need to get the login ticket from it before I run the POST request to submit the form, which is the "hidden" type input element with name "lt". (i.e. line with <input type="hidden" name="lt" value="LT-000000-b4LktCXyzXyzXyzXyzXyzXyz" />, and I need to parse the "value").
I've wrote some code, but it seems cannot find out this input element. Here is my C program's function:
const char * parse_login_ticket_old(char * raw_html)
{
// Parse HTML into Gumbo memory structure
GumboOutput * gumbo_output = gumbo_parse(raw_html);
// Prepare the node
GumboNode * gumbo_root = gumbo_output->root;
assert(gumbo_root->type == GUMBO_NODE_ELEMENT);
assert(gumbo_root->v.element.children.length >= 2);
const GumboVector* root_children = &gumbo_root->v.element.children;
GumboNode* page_body = NULL;
for (int i = 0; i < root_children->length; ++i)
{
GumboNode* child = root_children->data[i];
if (child->type == GUMBO_NODE_ELEMENT && child->v.element.tag == GUMBO_TAG_BODY)
{
page_body = child;
break;
}
}
assert(page_body != NULL);
GumboVector* page_body_children = &page_body->v.element.children;
for (int i = 0; i < page_body_children->length; ++i)
{
GumboNode* child = page_body_children->data[i];
GumboAttribute * input_name_attr = gumbo_get_attribute(&child->v.element.attributes, "name");
if (child->type == GUMBO_NODE_ELEMENT && child->v.element.tag == GUMBO_TAG_INPUT && strcmp(input_name_attr->value, "lt") == 0)
{
GumboAttribute * input_value_attr = gumbo_get_attribute(&child->v.element.attributes, "value");
return input_name_attr->value;
}
}
return NULL;
}
In case someone need for debugging, here is a example of our schools page. Possible sensitive data has been removed.
<body>
<div id="wrapper">
<div id="contentArea" role="main">
<div class="form login" role="form">
<h2 class="hidden">Login</h2>
<form id="fm1" class="fm-v clearfix" action="/schoolcas/login?jsessionid=1234567890" method="post"><div class="formRow">
<label for="username" class="label">Student ID</label>
<div class="textBox">
<input id="username" name="username" class="schoolcas text" aria-required="true" type="text" value="" size="25" maxlength="25"/></div>
</div>
<div class="formRow">
<label for="password" class="label">Password</label>
<div class="textBox">
<input id="password" name="password" class="schoolcas text" aria-required="true" type="password" value="" size="25" autocomplete="off"/></div>
</div>
<div class="formRow">
<input type="hidden" name="lt" value="LT-000000-b4LktCXyzXyzXyzXyzXyzXyz" />
<input type="hidden" name="execution" value="e2s1" />
<input type="hidden" name="_eventId" value="submit" />
<input class="button grey submit" name="submit" value="Login" type="submit" />
</div>
</form>
</div>
</div>
</div>
</body>
Anyway, my program seems just stop at the top of the body element and it returns NULL later on.
So I would like to know how to do a correct search, and find out the input element I need?
I've figured it out by myself from the Google sample code (https://github.com/google/gumbo-parser/blob/master/examples/find_links.cc).
Here's the code. It's crappy but it works anyway.
const char * find_attribute(GumboNode * current_node, GumboTag element_tag_type,
char * element_term_key, char * element_term_value, char * desired_result_key)
{
const char * lt_token = NULL;
// Return NULL if it is in WHITESPACE
if (current_node->type != GUMBO_NODE_ELEMENT)
{
return NULL;
}
// Set the element's term key,
// e.g. if we need to find something like <input name="foobar"> then element search term key is "name",
// and element search value is "foobar"
GumboAttribute* lt_attr = gumbo_get_attribute(&current_node->v.element.attributes, element_term_key);
if (lt_attr != NULL && current_node->v.element.tag == element_tag_type && (strcmp(lt_attr->value, element_term_value) == 0))
{
lt_token = gumbo_get_attribute(&current_node->v.element.attributes, desired_result_key)->value;
return lt_token;
}
GumboVector* children = &current_node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i)
{
lt_token = find_attribute(children->data[i], element_tag_type,
element_term_key, element_term_value, desired_result_key);
// Force stop and return if it gets a non-null result.
if(lt_token != NULL)
{
return lt_token;
}
}
}

Change value of <input type> when <select> change value MySql

i need your help for a simple question:
I have a form and i need that when user select another value iin a , it will change all values of of form.
My code is as follow:
<form action="updatecost.jsp" method="post" onsubmit=" return check(this)">
<tr>
<td><i> choice cost</i></td>
<td align="left"><select name="oldcost">
<%
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","pass");
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * FROM cost");
String id = "";
String year="";
String time="";
String cf="";
while (rs.next()) {
id = rs.getString("IdCost");
year=rs.getString("year");
time=rs.getString("time");
cf=rs.getString("CF");
%>
<option value="<%=id%>"><%=year%></option>
<%
}
%>
</select></td>
<br>
<td><i><font color="#660033"> actual year</font></i></td>
<br>
<input type="text" name="year" value="<%=year%>" size="25" /></td>
<br>
<td><i><font color="#660033">actual cost </font></i></td>
<br>
<input type="text" name="cost" value="<%=cost%>" size="25" /></td>
<br>
<td><i><font color="#660033"> cf </font></i></td>
<br>
<input type="text" name="cf" value="<%=cf%>" size="25" /></td>
<br>
<br>
It is better to save all of the results into ArrayList<Cost> costs then do the following:
Javascript:
var ids = new Array(),
years = new Array(),
times = new Array(),
cfs = new Array();
<%
for(Cost c: costs) {
%>
ids.push("<%=c.getIdCost()%>");
years.push("<%=u.getYear()%>");
times.push("<%=u.getTime()%>");
cfs.push("<%=u.getCF()%>");
<%
}
%>
Then insert an onchange="setCost(<%=id%>);" function into the select and add the JavaScript function
function setCost(id) {
for(var i = 0; i < ids.length; i++) {
if(ids[i] == id) {
document.getElementsByName("years")[0].value = years[i];
document.getElementsByName("cost")[0].value = costs[i];
document.getElementsByName("cf")[0].value = cfs[i];
}
}
}
Try this <select><%for(Cost c: costs) {%><option value="<%=c.getIdCost()%>" onchange="setCost(<%=c.getIdCost()%>)"><%=c.getYear()%></option><%}%></select>

AngularJs File Upload in asp.net mvc

here is what I've tried till now
I cant send that file to my action result, its showing me null,
<form ng-show="divPatient" name="PatientForm" ng-submit="AddUpdatePatient()">
<table>
<tr>
<td>
<input class="form-control" type="text" readonly placeholder="Key (Automatic)" ng-model="PatientID" />
</td>
<td>
<input id="FormFocus" name="FirstName" class="form-control" type="text" placeholder="FirstName" ng-model="FirstName" ng-minlength="3" required />
</td>
<td>
<input name="LastName" class="form-control" type="text" placeholder="LastName" ng-model="LastName" ng-minlength="3" required />
</td>
<td>
<input class="form-control" type="text" placeholder="Disease" ng-model="Disease" name="Disease" ng-minlength="3" required />
</td>
<td>
<input class="form-control" type="number" placeholder="Phone No." ng-model="PhoneNo" name="PhoneNo" ng-pattern="/^[789]\d{9}$/" required />
</td>
<td>
<input type="file" onchange="angular.element(this).scope().selectFileforUpload(this.files)" accept="image/*" class="form-control" ng-model="PhotoURL" value="{{PhotoURL}}" required />
</td>
<td colspan="2">
<input type="submit" value="save" class="btn btn-success" ng-disabled="PatientForm.PhoneNo.$dirty && PatientForm.PhoneNo.$invalid || PatientForm.LastName.$dirty && PatientForm.LastName.$invalid || PatientForm.FirstName.$dirty && PatientForm.FirstName.$invalid || PatientForm.Disease.$dirty && PatientForm.Disease.$invalid" />
<input type="button" value="cancel" class="btn btn-primary" ng-click="CancelForm()" />
</td>
</tr>
<tr>
<td></td>
<td><span class="eror-text" ng-show="PatientForm.FirstName.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.LastName.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.Disease.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.PhoneNo.$error.pattern">Invalid phone no</span></td>
</tr>
</table>
</form>
$scope.selectFileforUpload = function (files) {
$scope.selectedFile = files;
}
$scope.AddUpdatePatient = function () {
var file = $scope.selectedFile[0];
var Patient = {
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Disease: $scope.Disease,
PhoneNo: $scope.PhoneNo
};
var getData = angularService.AddPatient(Patient,filee);
getData.then(function (msg) {
GetAllPatients();
alert(msg.data);
$scope.divPatient = false;
}, function () {
alert('Error in adding record');
});
}
here is my service code
this.AddPatient = function (patient, file) {
// this showing me file object thats fine
alert("in services" + filee);
// i think something wrong here we shouldn't or can't send the file to actionresult like this
var response = $http({
method: "post",
url: "AddPatient",
data: JSON.stringify(patient),
dataType: "json",
// something wrong here ??
file : file
});
return response;
}
amd last my method in my controller
public string AddPatient(Patient patient,HttpPostedFileBase file)
{
// I'm getting patient data that is fine, but file is showing me null
}
is anything wrong with my service method ??? or do you know how to send form along with files to actionresult or any method in the mvc controller, i heard some pleople do it by using "new FormData", but i dont know that, but i'm willing to learn it or use it, if that solves my problem