ASP Razor Web Pages - Form Submit is Moving My Data - html

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.

Related

Attempt to read property "name" on array

I am trying to enter data inside database table via form. I have created an instance of Model and accessed the columns of that table and assigned the input names of form but when I enter data an submit it says Attempt to read property "name" on array. Can anyone guide me if there is anything wrong.
Code of Controller where im inserting datas to database
class UserController extends Controller
{
function registerUser(Request $req)
{
$data = $req->input();
$user_model = new User;
$user_model->fullname = $data->name;
$user_model->mobile = $data->mobile;
$user_model->email = $data->email;
$user_model->password = $data->password;
$user_model->save();
return "registered successfully";
}
}
Code of Form
<div class="register-form">
<h4>Sign Up</h4>
<form method="post" action="register">
#csrf
<input type="text" name="name" placeholder="Full Name" size="40">
<br>
<input type="tel" name="mobile" placeholder="Mobile number" size="40">
<br>
<input type="email" name="email" placeholder="Email" size="40">
<br>
<input type="password" name="password" placeholder="Password" size="40">
<br>
<input id="submit_btn" type="submit" placeholder="Sign Up" size="40">
<hr>
<p>Already, have an account <span href="#" id="sign-in-link">Log In</span></p>
</form>
</div>
function registerUser(Request $req)
{
$user_model = new User;
$user_model->fullname = $req->name;
$user_model->mobile = $req->mobile;
$user_model->email = $req->email;
$user_model->password = bcrypt($req->password); //laravel hashed password
$user_model->save();
return "registered successfully";
}
$req->input is an array. Access it like so.
$user_model->fullname = $data['name'];
$user_model->mobile = $data['mobile'];
$user_model->email = $data['email'];
$user_model->password = $data['password'];

Inserting dynamic table data to mysql in jsp

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();
}
}
}

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
};

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;
}
}
}

Why wont <button type="submit"> work?

I have a standard HTML form, and the button is not working. I know it is directing to the correct page, and as far as I can see everything looks perfect.
It lets me click the button, but then nothing happens, it doesn't direct me to the send.php page or anything.
<form method="post" action="http://www.URL.net/send.php">
<p>
<label for="name">Name <span class="required">*</span></label>
<input type="text" name="name" id="name">
</p>
<p>
<label for="email">Email <span class="required">*</span></label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject">
</p>
<p>
<label for="subject">Message <span class="required">*</span></label>
<textarea name="message" id="message" cols="45" rows="10"></textarea>
</p>
<div class="fBtn">
<button type="submit" name="submit" id="submit" class="regButton"><i class="icon-paper-plane"></i>Send Message</button>
</div>
</form>
Also, I have tried using <input type="submit" name="submit" id="submit" class="regButton" value="Send Message" /> as well, but it also isn't working for some odd reason.
Tested in Chrome and IE11.
EDIT Here is the JS for form vaildation:
$('#submit').click(function(){
$('input#name').removeClass("errorForm");
$('textarea#message').removeClass("errorForm");
$('input#email').removeClass("errorForm");
var error = false;
var name = $('input#name').val();
if(name == "" || name == " ") {
error = true;
$('input#name').addClass("errorForm");
}
var msg = $('textarea#message').val();
if(msg == "" || msg == " ") {
error = true;
$('textarea#message').addClass("errorForm");
}
var email_compare = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var email = $('input#email').val();
if (email == "" || email == " ") {
$('input#email').addClass("errorForm");
error = true;
}else if (!email_compare.test(email)) {
$('input#email').addClass("errorForm");
error = true;
}
if(error == true) {
return false;
}
var data_string = $('.contactForm form').serialize();
$.ajax({
type: "POST",
url: $('.contactForm form').attr('action'),
data: data_string,
success: function(message) {
if(message == 'SENDING'){
$('#success').fadeIn('slow');
}
else{
$('#error').fadeIn('slow');
}
}
});
return false;
});
You appear to have some JavaScript that automatically submits every form using AJAX. Since you’re on the domain trishajohnson.net, the same-origin policy prevents JavaScript from opening requests to a (slightly) different domain – www.trishajohnson.net.
There’s an easy fix, though – just use the path part. It’s cleaner anyway.
<form method="POST" action="/tj/send.php">