Remove error message in login page when it matches - javascript

I have a login page and I have the API for matching the password. If the password doesn't match it will show an error message but my problem is if the password is matching also it showing an error message. because am looping the data so every time it is checking I need to break the loop if it matches how to do. Here is my
code
HTML
$(document).ready(function() {
localStorage.removeItem('role');
$(".login-error").hide();
$("#login").on("submit", function(e) {
e.preventDefault();
var form_data = $('#login').serialize();
var username = $("#name").val();
var pwd = $("#password").val();
$.ajax({
url: "https://api.myjson.com/bins/qt7fk",
type: "GET",
dataType: "json",
success: function(data) {
console.log(typeof(data));
// alert(JSON.stringify(data));
var arr = data;
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.role);
var pass = obj.password;
// var decryptedBytes = CryptoJS.AES.decrypt(obj.password, "password");
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'password');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
// alert(plaintext);
var role = obj.role;
if (role == "User") {
if (username == obj.name && pwd == plaintext) {
alert("New role");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./job-insert.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
}
} else {
if (username == obj.name && pwd == plaintext) {
alert("Login succes");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./dashboard.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
document.getElementById('message').innerHTML = "Please enter a correct login and password"
}
}
})
},
error: function(data) {
console.log(data);
}
});
});
});

I have forked and break your code when the password gets matched. You may test this from here: code
$(document).ready(function() {
localStorage.removeItem('role');
$(".login-error").hide();
$("#login").on("submit", function(e) {
e.preventDefault();
var form_data = $('#login').serialize();
var username = $("#name").val();
var pwd = $("#password").val();
$.ajax({
url: "https://api.myjson.com/bins/qt7fk",
type: "GET",
dataType: "json",
success: function(data) {
console.log(typeof(data));
// alert(JSON.stringify(data));
var arr = data;
var BreakException = {};
try {
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.role);
var pass = obj.password;
// var decryptedBytes = CryptoJS.AES.decrypt(obj.password, "password");
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'password');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
// alert(plaintext);
var role = obj.role;
if (role == "User") {
if (username == obj.name && pwd == plaintext) {
alert("New role");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./job-insert.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
}
} else {
if (username == obj.name && pwd == plaintext) {
alert("Login succes");
document.getElementById('message').innerHTML = "Success"
throw BreakException;
/* window.location.href = "./dashboard.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
document.getElementById('message').innerHTML = "Please enter a correct login and password"
}
}
})
} catch (e) {
if (e !== BreakException) throw e;
}
},
error: function(data) {
console.log(data);
}
});
});
});
NOTE: You can break forEach like other loops. To make this thing done you need to add your code in try-catch and throw exception when the password gets matched. That is what I have done in your above code.

Related

how do i save my login details and redirect page properly?

** i am trying to do save login details and it works but when signin(true) fuction called page get reload infinity times **
signin(true)
// doing sign in
function onlogin(dataResult, is_check_login) {
$("#preloader").show();
var dataResult = JSON.parse(dataResult);
if (dataResult.statusCode == 200) {
$("#preloader").hide();
var signedin_user_id = dataResult.row_id;
// open dashboard if already logged in
window.location.href = '../page/index.html';
document.getElementById("dashboard_name").innerHTML = dataResult.name;
} else if (dataResult.statusCode == 201) {
$("#preloader").hide();
if (is_check_login) {
//open sign in form if not logged in
window.location.href = '../page/signin.html';
} else {
$("#preloader").hide();
console.log('invalid login');
}
}
}
function sign_in(is_check_login = false) {
var signin_email = $('#signin_email').val();
var signin_password = $('#signin_password').val();
if (is_check_login || (signin_email != "" && signin_password != "")) {
$.ajax({
url: `https://www.name.com/page/php/${is_check_login ? "checklogin" : "login"}.php`,
type: "POST",
data: {
signin_email: signin_email,
signin_password: signin_password
},
cache: false,
success: function (result) {
onlogin(result, is_check_login);
}
});
} else {
alert('Please fill all the field !');
}
}

'$' and 'document' are not defined - JQuery Mobile

JSHint Problems. console and FBT are also not defined.
As a result my button in page-signup does not work.
................................................................................................................................................................
(function () {
var emailAddressIsValid = function (email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
var passwordsMatch = function (password, passwordConfirm) {
return password === passwordConfirm;
};
var passwordIsComplex = function (password) {
// TODO: implement password complexity rules here. There should be similar rule on the server side.
return true;
};
$(document).delegate("#page-signup", "pagebeforecreate", function () {
var $signUpPage = $("#page-signup"),
$btnSubmit = $("#btn-submit", $signUpPage);
$btnSubmit.off("tap").on("tap", function () {
var $ctnErr = $("#ctn-err", $signUpPage),
$txtFirstName = $("#txt-first-name", $signUpPage),
$txtLastName = $("#txt-last-name", $signUpPage),
$txtEmailAddress = $("#txt-email-address", $signUpPage),
$txtPassword = $("#txt-password", $signUpPage),
$txtPasswordConfirm = $("#txt-password-confirm", $signUpPage);
var firstName = $txtFirstName.val().trim(),
lastName = $txtLastName.val().trim(),
emailAddress = $txtEmailAddress.val().trim(),
password = $txtPassword.val().trim(),
passwordConfirm = $txtPasswordConfirm.val().trim(),
invalidInput = false,
invisibleStyle = "bi-invisible",
invalidInputStyle = "bi-invalid-input";
// Reset styles.
$ctnErr.removeClass().addClass(invisibleStyle);
$txtFirstName.removeClass(invalidInputStyle);
$txtLastName.removeClass(invalidInputStyle);
$txtEmailAddress.removeClass(invalidInputStyle);
$txtPassword.removeClass(invalidInputStyle);
$txtPasswordConfirm.removeClass(invalidInputStyle);
// Flag each invalid field.
if (firstName.length === 0) {
$txtFirstName.addClass(invalidInputStyle);
invalidInput = true;
}
if (lastName.length === 0) {
$txtLastName.addClass(invalidInputStyle);
invalidInput = true;
}
if (emailAddress.length === 0) {
$txtEmailAddress.addClass(invalidInputStyle);
invalidInput = true;
}
if (password.length === 0) {
$txtPassword.addClass(invalidInputStyle);
invalidInput = true;
}
if (passwordConfirm.length === 0) {
$txtPasswordConfirm.addClass(invalidInputStyle);
invalidInput = true;
}
// Make sure that all the required fields have values.
if (invalidInput) {
$ctnErr.html("<p>Please enter all the required fields.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
return;
}
if (!emailAddressIsValid(emailAddress)) {
$ctnErr.html("<p>Please enter a valid email address.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtEmailAddress.addClass(invalidInputStyle);
return;
}
if (!passwordsMatch(password, passwordConfirm)) {
$ctnErr.html("<p>Your passwords don't match.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtPassword.addClass(invalidInputStyle);
$txtPasswordConfirm.addClass(invalidInputStyle);
return;
}
if (!passwordIsComplex(password)) {
// TODO: Use error message to explain password rules.
$ctnErr.html("<p>Your password is very easy to guess. Please try a more complex password.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtPassword.addClass(invalidInputStyle);
$txtPasswordConfirm.addClass(invalidInputStyle);
return;
}
$.ajax({
type: 'POST',
url: FBT.Settings.signUpUrl,
data:"email=" + emailAddress + "&firstName=" + firstName + "&lastName=" + lastName + "&password=" + password + "&passwordConfirm=" + passwordConfirm,
success: function (resp) {
console.log("success");
if (resp.success === true) {
$.mobile.navigate("signup-succeeded.html");
return;
}
if (resp.extras.msg) {
switch (resp.extras.msg) {
case FBT.ApiMessages.DB_ERROR:
case FBT.ApiMessages.COULD_NOT_CREATE_USER:
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! A problem occured while trying to register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
break;
case FBT.ApiMessages.EMAIL_ALREADY_EXISTS:
$ctnErr.html("<p>The email address that you provided is already registered.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtEmailAddress.addClass(invalidInputStyle);
break;
}
}
},
error: function (e) {
console.log(e.message);
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! A problem occured while trying to register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
}
});
});
});
})();

location.href not working

I have used location.href in my earlier days but now its not redirecting to page. here is my code
function AuthenticateUserWithPage() {
var UId = $('#amwayId').val();//username
var UPw = $('#amwayPw').val();//password
var ischecked = $('#idSave').is(':checked');// check remember me checkbox status
if (UId != '' && UPw != '') {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../KPPRMobService/PNBMobWebService.asmx/IsValidUserWithPage",
data: JSON.stringify({ username: UId, password: UPw, ischecked: ischecked }),
async: false,
success: function (data) {
var obj = data.d;
if (obj != "FALSE") {
var targetUrl = "http://" + window.location.host + obj;
window.location.href = targetUrl;
//window.location.replace(targetUrl);
return false;
}
else {
$('#amwayId').val('');
//if username or password is invalid
alert("Please check your ID or password. The ID is not registered or the ID/ password is wrong.");
}
},
error: function (result) {
//if error occured.
$('#amwayId').val('');
alert("You cannot log in. Contact support center for further inquiries..");
}
});
}
else {
//if username or password is null
alert("Please enter ID/ password.");
return false;
}
}
I use this link as reference: reference.Thanks in Advance.
Php:
$form_data = array();
$form_data['message'] = "success";
$form_data['redirect'] = "http://www.example.com/example";
echo json_encode($form_data)
Ajax:
if (data.message == 'success') {
window.location.href = data.redirect;
return false;
}else if(){
etc...
}

Validation error not displaying with AJAX

I have been struggle with this now for two days and I do not know where the problem is.
When I leave the textbox the Ajax call is correct and the result are returned as a true or false and the success: function is executing.
The problem is that the image and error text is not displaying next to the textbox. If I type in more than 50 characters in the textbox the "Must be under 50 characters" message is showing but it I type in a user name that already exist the message is not showing.
What am I missing? Any suggestions?
I use a DevExpress Text Box
Html.DevExpress().Label(
edtSettings =>
{
edtSettings.ControlStyle.CssClass = "label";
edtSettings.Text = "User Name:";
edtSettings.AssociatedControlName = "UserName";
}
)
.Render();
Html.DevExpress().TextBox(
edtSettings =>
{
edtSettings.Name = "UserName";
edtSettings.ControlStyle.CssClass = "editor";
edtSettings.ShowModelErrors = true;
edtSettings.Width = 100;
edtSettings.Properties.ValidationSettings.Assign(IserValidationHelper.UserNameValidationSettings);
edtSettings.Properties.ClientSideEvents.Validation = "OnNameValidation";
edtSettings.ControlStyle.BackColor = System.Drawing.Color.LightYellow;
}
)
.Bind(DataBinder.Eval(IserUser, "UserName"))
.Render();
I have the following JavaScript.
<script type="text/javascript">
function OnNameValidation(s, e) {
if (e.value == null)
e.isValid = false;
$.ajax({
type: 'POST',
url: '/Admin/CheckUsername',
dataType: 'json',
data: { userName: e.value },
error: function () { alert("error"); },
success: function (Data) {
if (Data.result == true) {
e.isValid = false;
e.errorText = "User Exits";
};
}
});
var name = e.value;
if (name == "")
e.isValid = false;
if (name.length > 50) {
e.isValid = false;
e.errorText = "Must be under 50 characters";
}
}
I have the following method in my controller.
[HttpPost]
public ActionResult CheckUsername(string userName)
{
bool status = WebSecurity.UserExists(userName);
return Json(new { result = status });
}
The problem was with my $.ajax call. I had to include the setting async (async:false,) as the default async is true. It is working now correctly.
function OnNameValidation(s, e) {
if (e.value == null)
e.isValid = false;
$.ajax({
type: 'POST',
url: '/ISERAdmin/CheckUsername',
dataType: 'json',
async:false,
data: { userName: e.value },
error: function () { alert("error"); },
success: function (Data) {
if (Data.result == true) {
e.isValid = false;
e.errorText = "User Exits";
};
}
});
var name = e.value;
if (name == "")
e.isValid = false;
if (name.length > 56) {
e.isValid = false;
e.errorText = "Must be under 56 characters";
}
}

Why don't work my function xmlParser(). Help me please

Hello everybody. I have a problem with my code. I use the jquery framework. When I want to call $.ajax(requestOptions), function xmlParser(xml) don't working.
I try to find a resolve this problem, but I can't nothing find.
$(document).ready(function () {
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser //Calling function
};
function xmlParser(xml) {
$("#load").fadeOut();
$(xml).find("Valute").each(function() {
$("#outputListValutes").append(
"<option value=" + $(this).find("CharCode").text() + ">" + $(this).find("CharCode").text() + "</option>");
});
};
$.ajax(requestOptions);
$("#clear").click(function() {
var sumValue = document.getElementById("sum").value = "";
var resValue = document.getElementById("result").value = "";
});
$("#convert").click(function(xml) {
//var selectCurrency = $("#inputListCurrency").val();
//findData(xml);
}(requestOptions));
function findData(xml) {
var decimalOnly = /^\s*-?[1-9]\d*(\.\d{1,2})?\s*$/;
try{
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if(value == "") throw new Error("Empty value");
else if(!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if(value < 0) throw new Error("Value isn't to be below zero");
else if(isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function() {
if(shortName == $(this).find("CharCode").text()) {
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch(e) {
alert(e);
}
}
});
change the success parameter of the request to use the xmlParser function (forgot () ):
var requestOptions = {
type: "GET", //The method
url: "Course_Valute_02-07-2014.xml", //It is reference on xml file
dataType: "xml", //The type of data
crossDomain: true, //Allow to do the cross-domain request
success: xmlParser(data) //Calling function
};
I found the solution this promlem. I am happy.
var courseFilePath = "xml/Course_Currency_02-07-2014.xml";
var listCurrency = [];
function insertOptions(){
for (var i = 0; i < listCurrency.length; ++i){
$("#outputListCurrency").append(
"<option value=" + listCurrency[i] + ">" + listCurrency[i] + "</option>");
}
}
function xmlParser(xml){
$("#load").fadeOut();
$(xml).find("Valute").each(function(){
var value = $(this).find("CharCode").text();
listCurrency.push(value);
});
listCurrency.sort();
};
function findData(xml){
var decimalOnly = /^\s*-?[0-9]\d*(\.\d{1,2})?\s*$/;
try {
var shortName = $("#outputListCurrency").val();
var value = $("#sum").val();
if (value == "") throw new Error("Empty value");
else if (!decimalOnly.test(value)) throw new Error("value must be of decimal digits");
else if (value < 0) throw new Error("Value isn't to be below zero");
else if (isNaN(parseFloat(value))) throw new Error("Value isn't to be as symbols");
$(xml).find("Valute").each(function(){
if (shortName == $(this).find("CharCode").text()){
var nominal = $(this).find("Nominal").text();
var course = $(this).find("Value").text();
var result = parseFloat(value) * parseFloat(nominal) / parseFloat(course);
document.getElementById("result").value = Number(result).toFixed(2);
}
});
}
catch (e){
alert(e);
}
}
$(document).ready(function(){
$.ajax({
type: "GET", //The method of sending for data
url: courseFilePath, //It is reference on xml file
dataType: "xml", //The type of data
success: function(xml){
xmlParser(xml);
insertOptions();
}
});
//insertOptions();
$("#clear").click(function() {
document.getElementById("sum").value = "";
document.getElementById("result").value = "";
});
$("#convert").click(function() {
var selectCurrency = $("#inputListCurrency").val();
$.get(courseFilePath, findData, "xml");
});
});

Categories