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>
Related
I have an html form. The form sends login request to server. The html response from server is put in an iframe.
$(document).ready(function(){
$("#submit").click(function(event){
$("#dummyframe").on('load',function() {
var myiframe = $("#dummyframe").val();
var iframedocument = myiframe.contentDocument;
var response = iframedocument.queryselector("pre");
var errormessage = '{"code":500,"message":"入力項目に誤りがあります","data":{}}';
if (response == errormessage ){
alert('wrong password');
}
else {
alert('password is ok');
}
});
});
});
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form method="post" target="dummyframe" action="https://kintai.jinjer.biz/v1/sign_in">
<input name="company_code" type="hidden" value="1234" />
<input name="email" type="hidden" value="1234" />
<input name="password" type="hidden" value="1234" />
<input type="submit" value= "submit" id= "submit" />
</form>
I want to read response from the server to validate password. If I get error message from server, I want to alert "wrong password" in my html page. Am I missing something? It doesn't work. The code doesn't seem incorrect. Your help is greatly appreciated.
You need to change your script to below:
$(document).ready(function(){
$("#submit").click(function(event){
$("#dummyframe").on('load',function() {
var myiframe = $("#dummyframe");
var iframedocument = myiframe.contentDocument;
if (iframedocument.document) iframedocument = iframedocument.document;
var response = iframedocument.queryselector("pre").innerHTML;
var errormessage = '{"code":500,"message":"入力項目に誤りがあります","data":{}}';
if (response == errormessage ){
alert('wrong password');
}
else {
alert('password is ok');
}
});
});
});
I am trying to check the users input on my login form.
I am sending an HTTP request to the server to check the database for the username.
Here is the network URL:
https://bceec5a5-eba3-49e3-b255-d3976d185fad-ide.cs50.xyz:8080/user_name?username=fabianomobono
Here's the html
<form id="login_form" action='/home' method='post'>
<input id="login_credentials_username" name='login_username' type='text' placeholder='Username' >
<input id="login_credentials_password" name='login_password' type='password' placeholder="Password" >
<button class="btn btn-primary" type='submit'>Log in</button>
</form>
This is the JS code:
$('#login_form').ready(function() {
$('#login_form').on('submit', function(e) {
e.preventDefault();
logincheck();
});
});
function logincheck(){
var username = document.getElementById("login_credentials_username").value;
var password = document.getElementById("login_credentials_password").value;
if (username == ''){
alert("no user");
return false;
}
else if (password == ''){
alert('no password');
return false;
}
else if (password && username){
alert(password + username);
console.log(username)
$.get('/user_name?username' + username, function(r){
if (r === false){
alert('python returned false');
return false;
}
else{
alert('python returned true');
return true;
}
});
return false;
}
else {
return true;
}
}
and here is the python function:
#app.route("/user_name", methods=["GET"])
def login_usercheck():
print(Fore.GREEN + "user_check function, line 171")
username = (request.args.get('login_username'),)
print(username)
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("SELECT username FROM users WHERE username =?", username)
old_user = c.fetchall()
if len(old_user) > 0:
return jsonify(True)
else:
return jsonify(False)
The problem is that my username variable in the python function always returns NULL. I tried all combinations of,(request.form.get, request.args.get... and so on)
Funny thing is I have a similar function to check for the register credentials and that one works just fine. I can't seem to figure out what the problem is...
Here's what I get in the terminal:
(None,)
192.168.164.98 - - [05/Nov/2019 17:54:01] "GET /user_name?username=cf HTTP/1.0" 200 -
username = request.args.get('username')
$.get('/user_name?username' + username,...
the bold parts need to match
it was pointed out to me by another user...
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 have a simple log in and I cannot get the validation to work at all. I was wondering if someone could help.
HTML:
<div class="login">
<h2>Sign In</h2>
<form id="frmLogin" method="post">
Username: <input id="txtUsername" name="txtUsername" type="text" /><br/>
Password: <input name="txtPassword" type="password" /> <br/>
<button onClick="validateLogin()">Log In</button>
</form>
</div><!-- End of Login Section -->
Javascript:
<script>
function validateLogin()
{
var userName = document.getElementsByID('txtUsername').value;
var invalidForm = 0;
if(userName == "")
{
alert("Username cannot be blank!");
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}//end if
}
</script>
At the moment I'm just testing for an empty username, once I can get this working I'll continue on with the rest.
Thank you!
To get and element by ID the function name is getElementById and not getElementsByID, besides, javascript is case sensitive so getElementByID does not work.
function validateLogin()
{
var userName = document.getElementById('txtUsername').value;
var invalidForm = 0;
if(userName == "")
{
alert("Username cannot be blank!");
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}//end if
}
Do your jquery code something like these :-
<script>
function validateLogin()
{
var userName = document.getElementById('txtUsername').value;
var invalidForm = 0;
var errMessage = ""
if(userName === "")
{
errMessage = "Username cannot be blank!";
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}
else if (invalidForm == 1)
{
alert(errMessage);
return false;
}
}
</script>
It may help you.
i have a problem with validating if the username is already taken. I am trying to find out if the username already exists using the "post" method of jquery. But when executing this function, the script is always jumping to the end of the function and is doing the rest of the script first before executing the "post" command. Could you please review my code and help me?
$("#submit").click(function () {
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var passwort = document.getElementById("passwort").value;
var passwort2 = document.getElementById("passwort2").value;
var validate = false;
checkUsername();
if (validate == true) {
$.post("Login/register.php", {
username: username,
email: email,
passwort: passwort,
passwort2: passwort2,
}, function (info) {
$("#errorBox").empty();
$("#errorBox").html(info);
});
} else {
$('#register').submit(function () {
return false;
});
}
function checkUsername() {
username = document.getElementById("username").value;
// username = replaceUmlauts(username);
if (username.length > 0) {
document.getElementById("username").style.borderColor = "";
// document.getElementById("errorBox").innerHTML =
// "";
validate = true;
checkAvailability();
return false;
} else {
document.getElementById("username").style.borderColor = "red";
document.getElementById("errorBox").innerHTML = "Username muss länger als ein Zeichen sein";
// alert('Username must be longer than one sign');
validate = false;
return false;
}
}
function checkAvailability() {
$.post(
"Login/checkusername.php", {
username: username
},
function (result) {
// if the result is 1
if (result == 1) {
// show that the username is
// available
document
.getElementById("errorBox").innerHTML = "";
return false;
} else {
// show that the username is NOT
// available
document
.getElementById("errorBox").innerHTML = "Username nicht verfuegbar";
document
.getElementById("username").style.borderColor = "red";
validate = false;
return false;
}
});
}
return false;
});
edit: My html code :
<form id="register" >
<div id='registerpopup'>
<div class='close'></div>
<span class='ecs_tooltip'>Schließen mit ESC<span class='arrow'></span></span>
<div id='popup_content'> <!--your content start-->
<table border=0 cellspacing=10 cellpadding=20 align=center>
<div id="errorBox"></div>
<tr>
<th>
<p style="margin-top: 20px; margin-right: 5px">Username:</p>
<p style="margin-top: 18px; margin-right: 5px">E-Mail:<p>
<p style="margin-top: 16px; margin-right: 5px">Passwort:</p>
<p style="margin-top: 16px; margin-right: 5px">Passwort wdhl.:</p>
</th>
<th>
<p style="margin-top: 20px"><input id="username" name="username" type='text' size='30' maxlength='30' ><br></p>
<p><input id="email" name="email" type='text' size='30' maxlength='30'><br></p>
<p><input id="passwort" name="passwort" type='password' size='30' maxlength='30' ><br></p>
<p><input id="passwort2" name ="passwort2" type='password' size='30' maxlength='30'><br></p>
</th>
</tr>
</table>
<table border=0 cellspacing=10 cellpadding=20 align=center>
<tr>
<th>
<button id="submit" class="submit" type="submit" style="margin-top: 30px"> Registrieren </button>
</th>
</tr>
</table>
</div>
</div>
</form>
<script type="text/javascript" src ="js/checkregister.js"></script>
<div class='loader'></div>
<div id='backgroundPopup'></div>
I tried to change the ("#submit") to document.getElementById("submit") to get my code "more clean" but it does not seem to work.
You have a scope issue with your variable validate , I suggest you this in your function checkUsername():
if (username.length > 0) {
document.getElementById("username").style.borderColor = "";
// document.getElementById("errorBox").innerHTML =
// "";
return checkAvailability();
} else {
document.getElementById("username").style.borderColor = "red";
document.getElementById("errorBox").innerHTML = "Username muss länger als ein Zeichen sein";
// alert('Username must be longer than one sign');
return false;
}
, this in your function checkAvailability() :
if (result == 1) {
// show that the username is
// available
document.getElementById("errorBox").innerHTML = "";
return true;
} else {
// show that the username is NOT
// available
document.getElementById("errorBox").innerHTML = "Username nicht verfuegbar";
document.getElementById("username").style.borderColor = "red";
return false;
}
and var validate = checkUsername(); before your if statements in your main function
EDIT : This code is dirty, you should choose working with "old school JS" like document.getElementById for example, or jQuery (ex: $('#myId')), but the use of both is not recommanded
I don't have enough time to clean it all up, but this would be a good start. Pls note that I have used $.post("/echo/html/", { only for the demo purposes and commented the actual line as it wouldn't work in fiddle. Modify the code to suit your needs.
Demo#Fiddle
$("#register").on("submit", function (evt) {
evt.preventDefault();
var $username = $("#username");
var email = $.trim($("#email").val());
var passwort = $.trim($("#passwort").val());
var passwort2 = $.trim($("#passwort2").val());
var $errorBox = $("#errorBox");
var isUser = checkUsername();
if (isUser) {
checkAvailability();
}
function checkUsername() {
var usernameVal = $.trim($username.val());
if (usernameVal.length > 0) {
$username.css({borderColor: "none"});
return true;
} else {
$username.css({borderColor: "red"});
$errorBox.html("Username muss länger als ein Zeichen sein");
}
return false;
}
function checkAvailability() {
//$.post("Login/checkusername.php", {
$.post("/echo/html/", {
"username": $.trim($username.val())
}, function (result) {
// if the result is 1
if (result == 1) {
register().done(function() {
$errorBox.append("<p>Hurray!</p>");
});
} else {
// show that the username is NOT
// available
$errorBox.html("Username nicht verfuegbar");
$username.css({borderColor: "blue"});
return;
}
});
}
function register() {
//return $.post("Login/register.php", {
return $.post("/echo/html/", {
username: $.trim($username.val()),
email: email,
passwort: passwort,
passwort2: passwort2,
}, function (info) {
$errorBox.html(info);
});
}
});