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...
}
Related
** 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 !');
}
}
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.
I have a PHP file receiving data from Ajax but after receiving the data I am sending a success message from php using json_encode, but the message error is hit is being alerted even though the SQL query is successful. This process worked well for localhost but when I uploaded it in main server there is an error.
Here Is my JS file:
$(function() {
$("#userReg_btn").click(function(e) {
//user registration in
var array = [];
var flag = false;
var firstName = $("#uFn").val();
var lastName = $("#uLn").val();
var email = $("#uEa").val();
var pass = $("#uPn").val();
var mobile = $("#uMn").val();
var nID = $("#uNm").val();
var age = $("#uAn").val();
var prof = $("#uPc").val();
if (firstName == "" || lastName == "" || email == "" || pass == "" || mobile == "" || nID == "" || age == "" || prof == "") {
e.preventDefault();
alert("Please provide some input");
flag = false;
} else if (mobile.length != 11 || nID.length != 17) {
e.preventDefault();
alert("Please provide correct input");
flag = false;
} else {
array.push(firstName);
array.push(lastName);
array.push(email);
array.push(pass);
array.push(mobile);
array.push(nID);
array.push(age);
array.push(prof);
alert(array);
console.log(array);
flag = true;
}
if (flag == true) {
$.ajax({
url: "http://demoname.co/CustomerRegistration.php",
data: {
firstName: array[0],
lastName: array[1],
email: array[2],
pass: array[3],
mobile: array[4],
nID: array[5],
age: array[6],
prof: array[7]
},
type: "POST",
dataType: "json",
success: function(suc) {
alert("in success");
alert(suc);
console.log("success");
},
error: function(err) {
alert("error is hit");
alert(err);
console.log(err);
}
});
} else {
alert("Form error");
}
alert("USer Reg");
});
Here is my PHP file:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 2016 00:00:00 GMT');
// The JSON standard MIME header.
header('Content-type: application/json');
$con=mysql_connect("localhost","username", "password");
mysql_select_db("database name",$con);
$fname = $_POST['firstName'];
$lname=$_POST['lastName'];
$username=$_POST['email'];
$password=$_POST['pass'];
$phone=$_POST['mobile'];
$nid=$_POST['nID'];
$age=$_POST['age'];
$profession=$_POST['prof'];
$query="INSERT INTO customerregistration(FirstName,LastName,Username,password,PhoneNumber,NID,Age,Profession) VALUES('$fname','$lname','$username','$password','$phone','$nid','$age','$profession');";
if(mysql_query($query))
{
$suc= 'success';
echo json_encode($suc);
}
else
{
echo mysql_error();
}
?>
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";
}
}
I use jquery to validate the form, check the math-captcha and finally, send a mail.
The validation works fine and the mail works fine. There is only one problem. When my ajax returns false, the bool validCaptcha keeps always true...
$(document).ready(function() {
$("#confirm").on("click", function(e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function() {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function() {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function() {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
validCaptcha = false;
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
}
}
});
//Send email
if (validName == true && validEmail == true && validMessage == true && validCaptcha == true) {
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
}
else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
} else {
reloadCaptcha();
$("#inputcaptcha").val("");
}
});
});
In Firebug I see I get a 'false' back from checkCaptcha.php when e.g. I left the field blank of entered a wrong code.
checkCaptcha.php
session_start();
if ( !empty($_POST['inputcaptcha']) ) {
if ( $_POST['inputcaptcha'] == $_SESSION['security_number'] ) {
echo 'true';
}
else {
echo 'false';
}
}
else {
echo 'false';
}
To check I first checked the result-value from the captcha-ajax
alert(result)
//returned false as it should when leaving blank or entering wrong value
Then before calling the mail-ajax I called all bools
alert('validName='+validName+' & validEmail='+validEmail+' & validMessage='+validMessage+' & validCaptcha='+validCaptcha);
//validCaptcha was true, even when result was false...
What do I not see??
Simply put you can't do that since the validate captcha is an asynchronous request,
Instead you can move the email code to the validate captcha success handler like
$(document).ready(function () {
$("#confirm").on("click", function (e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function () {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function () {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function () {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
if (validName == true && validEmail == true && validMessage == true) {
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
reloadCaptcha();
$("#inputcaptcha").val("");
} else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
}
}
});
}
});
});