This is my form in the view..
SendCall is the method in controller to sending email..
#using (Html.BeginForm("SendCall", "Home", FormMethod.Post, new { id = "email-form" }))
{
<label>Name</label>
<input type="text" id="name" value=""/><span class="require"> *</span>
<label>Email:</label>
<input id="Email" type="text" />
<input type="submit" value="Submit" >
}
This is the action code..
[HttpPost]
public ActionResult SendCall(string Date, string Phone, string Name, string Email)
{
string username = "xxxxxx#gmail.com";
string password = "********";
NetworkCredential loginInfo = new NetworkCredential(username, password);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
string message = Name + Email; //I have shortened this line.
try
{
msg.From = new MailAddress("yourname#gmail.com", "My Website");
msg.To.Add(new MailAddress("email#gmail.com"));
msg.Subject = "Contact Message";
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.Send(msg);
return Content("Your message was sent successfully!");
}
catch (Exception)
{
return Content("There was an error... please try again.");
}
}
Can anyone suggest me how to validate this form? By adding some code in ajax code? I want client side validation and not with unobtrusive..
Related
I am trying to pass data from html input to a vanilla JS class constructor.
this is what I have tried.
class Users {
constructor(email,password) {
this.email = email;
this.password = password;
}
login(){
// url for endpoint
let url = "http://127.0.0.1:5000/api/v2/users/login"
alert(this.password)
// get login data from ui
let data = {
email : this.email,
password : this.password
};
}
let email = document.getElementById('email').value,
let password = document.getElementById('password').value
const user = new Users(email,password)
document.getElementById('login').addEventListener('submit', user.login())
It seems no data is passed to the email and password variables.
I have also tried to do this but the object is not called
class Users {
constructor(email,password) {
this.email = email;
this.password = password;
}
login(){
// user the data here
}
function load(event){
let email = document.getElementById('email').value,
let password = document.getElementById('password').value
const user = new Users(email,password)
user.login()
}
document.getElementById('login').addEventListener('submit', load)
Someone help me on how to work on this.
I have tried my best to refactor your code. Depending on what you want to do with the data, thats up to you. But in the below code, you can get the email and password in the login function
class Users {
constructor() {
}
login(){
let email = document.getElementById('email').value,
password = document.getElementById('password').value
alert(email, password)
}
}
const user = new Users();
const login = user.login
<input type="text" id="email" />
<input type="text" id="password" />
<button id="login" onclick="login()">submit</button>
I am trying to have my website call my login API, which I have tested from a separate app, and through Postman, and it runs fine. However when I run it through my website, it is not calling the API with the actual values inside the html input item.
Below is my HTML of my attributes:
<div class="container">
<label for="uname"><b>Username</b></label>
<input id= "username" type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input id= "password" type="password" placeholder="Enter Password" name="psw" required>
<button id="loginButton" type="button" class=""">login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
Below is my code for my website API call:
<script type="text/javascript">
document.getElementById("loginButton").onclick = function () {
var xhttp = new XMLHttpRequest();
console.log("login button clicked");
var usr = document.getElementById("username").value;
var psw = document.getElementById("password").value;
console.log(usr);
console.log(psw);
xhttp.open("GET", "http://serverAddress/checkHash/"+usr+"/"+psw+"/", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var response = (xhttp.responseText);
console.log("user logged in");
console.log("the response is:" + response);
//var value = (usr.concat(psw));
//console.log('concat value of both usr and psw is:');
//console.log(value);
if(response != "no") {
//this means the credentials are right
localStorage.setItem("session", usr);
location.href = "userSearch.php";
} else {
window.alert("Incorrect credentials");
}
};
</script>
Below is my Server code:
app.post('/createPhysician/', function(req, res) {
console.log("below is the req body for createPhysician");
console.log(req.body);
var createPromise = interact.createPhysician(
req.body.firstName,
req.body.lastName,
req.body.yearNum,
req.body.position,
req.body.isAttending,
req.body.highRiskTrained);
createPromise.then(function(createResponse) {
res.json("successful"); // returns the physicianID for the createUsers
}).catch(function(err) {
console.log(err);
console.log(req.body);
res.json("Terrible job you botched it");
});
});
Below is my interact sql file:
createPhysician: function(
firstName,
lastName,
yearNum,
position,
isAttending,
highRiskTrained) {
var qry = "insert into Physician (firstName, lastName, yearNum, position, isAttending, highRiskTrained) values ('"+firstName+"', '"+lastName+"', "+yearNum+", '"+position+"', "+isAttending+", "+highRiskTrained+");";
console.log("below is query ran in DBINteract");
console.log(qry);
return runQuery(qry);
}
the error I am getting is as follows:
below is the username given to server.js
[object HTMLInputElement]
below is the value of pass from app
[object HTMLInputElement]
below is the value from server side
TypeError: Cannot read property 'password' of undefined
I am trying to add a new Stop to my database. But I get a 401 error in asp.net.
.js file:
(function () {
"use strict";
angular.module("app-trips")
.controller("tripEditorController", tripEditorController);
function tripEditorController($routeParams, $http) {
var vm = this;
vm.tripName = $routeParams.tripName;
vm.stops = [];
vm.newStop = {};
vm.addStop = function () {
alert(vm.newStop.name);
$http.post("/api/trips/" + vm.tripName + "/stops", vm.newStop)
.then(function (response) {
vm.stops.push(vm.newStop);
};
}
}
.html file (input form):
<form novalidate name="newStopForm" ng-submit="vm.addStop()">
<div class="form-group">
<label for="">Date</label>
<input class="form-control" id="arrival" name="arrival" ng-model="vm.newStop.arrival" required />
</div>
<div class="form-group">
<label>Location</label>
<input class="form-control" id="name" name="name" ng-model="vm.newStop.name" required ng-minlength="3" />
</div>
<div>
<input type="submit" value="Add" class="btn btn-success" ng-disabled="newStopForm.$invalid" />
</div>
</form>
C# Post code:
[HttpPost("/api/trips/{tripName}/stops")]
public async Task<IActionResult> Post(string tripName, [FromBody]StopViewModel vm)
{
try
{
if (ModelState.IsValid)
{
var newStop = Mapper.Map<Stop>(vm);
var result =await _coordsService.GetCoordsAsync(newStop.Name);
if (!result.Succes)
{
_logger.LogError(result.Message);
}
else
{
newStop.Latitude = result.Latitude;
newStop.Longitude = result.Longitude;
}
_repository.AddStop(tripName, newStop, User.Identity.Name);
if (await _repository.SaveChangesAsync())
{
return Created($"/api/trips/{tripName}/stops/{newStop.Name}",
Mapper.Map<StopViewModel>(newStop));
}
}
}
catch (Exception ex)
{
_logger.LogError("Failed to save new Stop: {0}", ex);
}
return BadRequest("Failed to save new stop");
}
GeoCoordsService.cs:
public async Task<GeoCoordsResult> GetCoordsAsync(string name)
{
var result = new GeoCoordsResult()
{
Succes = false,
Message = "Failed to get coordinates"
};
var apiKey = _config["Keys:BingKey"];
var encodedName = WebUtility.UrlEncode(name);
var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={encodedName}&key={apiKey}";
var client = new HttpClient();
var json = await client.GetStringAsync(url);
var results = JObject.Parse(json);
var resources = results["resourceSets"][0]["resources"];
if (!resources.HasValues)
{
result.Message = $"Could not find '{name}' as a location";
}
else
{
var confidence = (string)resources[0]["confidence"];
if (confidence != "High")
{
result.Message = $"Could not find a confident match for '{name}' as a location";
}
else
{
var coords = resources[0]["geocodePoints"][0]["coordinates"];
result.Latitude = (double)coords[0];
result.Longitude = (double)coords[1];
result.Succes = true;
result.Message = "Success";
}
}
return result;
}
I have read, that this is probably caused because the data is not in the right format, does anyone know what would be the right format, my webpage returns error 400, but deeper in my C# I can see that function var json = await client.GetStringAsync(url);is returning an error 401 (Unotharized). I guess I should also add username somewhere, but I don't know where.
You're getting a 400 because the request you sent isn't what the server is expecting. Find out the object the server is expecting on that endpoint. Then form your request body to match that object.
I have a Database with some users in it, which have a username and a password.
I want to make a login form in JSP with 2 fields "login" and "password" if the input from the user is the same as in the database i want it to redirect to homepage.
I know how to do this in php but im completely new to jsp so i have really no idea where to start, i thought javascript would be needed to accomplish this.
I have already seen some comparable questions as mine but no answer seems to really work for me.
Here is my JSP Page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="<c:url value="/resources/css/style.css"/>">
<title>login</title>
</head>
<body>
<div class="login-block">
<h1>Login Page</h1>
<div class="inlog-block">
<form action="" method="post">
<p>Enter Username: </p>
<input type="text" name="username" required="required" /> <br>
<p>Enter password: </p>
<input type="password" name="password" required="required"/><br><br>
<input type="submit" name="loginbutton" value="Login"/>
</form>
</div>
</div>
</body>
</html>
Also i'm already able to get my users from the database in an arraylist in my model so maybe i need to use this in my JSP?
my Employeelist class:
public class EmployeeList {
private ArrayList<Employee> employees = new ArrayList<>();
public EmployeeList()
{
loadEmployees();
}
public void loadEmployees(){
DAOEmployee DAOE = new DAOEmployee();
employees = DAOE.LoadAllEmployees();
}
public ArrayList<Employee> getEmployees() {
return employees;
}
public void setEmployees(ArrayList<Employee> employees) {
this.employees = employees;
}
}
my DAOEmployee class:
public class DAOEmployee extends DAObject{
public ArrayList<Employee> LoadAllEmployees(){
String sql = "SELECT * FROM EMPLOYEE";
Employee e = null;
ArrayList<Employee> employees = new ArrayList<>();
try {
ResultSet rs;
Statement stmt = openConnection().createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
int ide = rs.getInt("id");
String first = rs.getString(2);
String last = rs.getString(3);
String mail = rs.getString(4);
String adres = rs.getString(5);
String zip = rs.getString(6);
String funct = rs.getString(7);
String user = rs.getString(8);
String pass = rs.getString(9);
e = new Employee(ide,first, last, mail, adres, zip, funct, user, pass);
employees.add(e);
}
}
catch (SQLException x) {
// TODO Auto-generated catch block
x.printStackTrace();
}
return employees;
}
}
And my DAObject class:
public class DAObject {
private String url = "jdbc:mysql://127.0.0.1/mydatabase";
private String user = "root";
private String password = "root";
public Connection conn = null;
public DAObject(){
}
public Connection openConnection(){
try{
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connection succesfull");
}
catch(SQLException e){
e.printStackTrace();
}
return conn;
}
public void CloseConnection(){
try{
conn.close();
}
catch(SQLException e){
e.printStackTrace();
System.out.println("");
}
}
}
You need a method to search for a especific user with a differente SQL instruction and you return a object Employee or boolean w/e you want from it:
String sql = "SELECT * FROM EMPLOYEE WHERE USER=? AND PASS=?";
In your servlet you call it and check if there is a registry for this user using the inputs values from your form.
String userName = req.getParameter("username");
Edit:
a)You need a method to search for this user, something like this (DAO layer example):
public User search(String userName, String password, Connection con) throws Exception{
User user = null;
String sql = "SELECT USERNAME, PASSWORD FROM T_USERS WHERE USERNAME=? AND PASSWORD=?";
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setString(1, userName);
pStmt.setString(2, password);
ResultSet rS = pStmt.executeQuery();
if(rS.next()){
user = new User(rS.getString("USERNAME"), rS.getString("PASSWORD"));
}
rS.close();
pStmt.close();
return user;
}
b) In you Servlet you check it in doPost method:
String user = req.getParameter("username");
String pass = req.getParameter("password");
Connection con = null;
try {
con = ConexaoFactory.getInst().getConnection("", "");
User user = BOClass.search(user, pass, con);
if(user == null){
//not found;
}else{
//found;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(con != null)
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
This is just a example how you can do it.
This is my simple html form that will pass username and password and returns a json array
<form class="form-signin" id="login" method="post" action="/Webservices/0.1/login"">
<input type="text" class="form-control" placeholder="email id" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="password" id= "password">
<button type="submit" name="submit" id="submit" >Sign in</button>
</form>
This is my route:
router.post('/login',function (req,res) {
var email = req.body.email;
var password = req.body.password;
var arrayParam = [];
var emailValidation = emailPattern.test(email);
arrayParam.push('email','password');
reqdParams.verifiyRequiredParameters(arrayParam, req.body, function (result) {
if (result.success == "0") {
res.json(result);
}
else if (email == '' || password == '' ) {
res.json({'success': '0', 'result': {}, 'errorMessage': "data should not be null"});
}
else if (!(emailValidation)) {
res.json({'success': '0', 'result': {}, 'errorMessage': 'not a valid email'});
}
else
{ password =new Buffer(password).toString('base64');
var userObject = {'email':email, 'password': password};
var verifyUserQuery = model.client.prepare("select userId,username,IFNULL(profilePicture,'') as profilePicture,email,password,profileType,IFNULL(profileId,'') as profileId,userType,IFNULL(token,'') as token,deviceName,osType,osVersion,isBlocked,isActive,ofActive,joinedDate from users where email = :email and password=:password");
model.client.query(verifyUserQuery (userObject ),function(err,rows){
if(rows.length> 0){
if(rows[0].isActive == 1){
var userProfile = rows[0];
res.json({'success':'1','result':{'message':'Valid User','userProfile':userProfile},'errorMessage':'No'});
}
else{
res.json({'success':'0','result':{},'errorMessage':'user is not verified'});
}
}
else
res.json({'success':'0','result':{},'errorMessage':'user Invalid'});
});
}
});
});
This code will return a json array:
{"success":"0","result":{},"errorMessage":"user Invalid"}
if success=0 i want to display error Message in html form.
if success-1 i want to redirect to another page.
how to do this?
var err = {"success":"0","result":{},"errorMessage":"user Invalid"},
holder = document.getElementById('errorholder');
if(err.success == '0'){
holder.innerHTML = err.errorMessage;
} else {
// redirect using window.location
}
HTML
<div id="errorholder"></div>