It works on localhost but not in server I. Another warning is
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check...
Here is my form:
<form action ="" method="post" id="frmlogin" class="text" onsubmit="return flogin();">
<input type="text" name="user" id="email" placeholder="Username*" required>
<input type="password" name="pass" id="password" placeholder="Password*" required>
<input type="submit" name="login" class="login loginmodal-submit" value="Login">
Here is my Javascript:
<script>
function flogin() {
$("#errorlog").html("");
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var request = $.ajax({
type: 'post',
url: 'action/login_action.php',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {email: email, password: password, login: "login"},
success: function (response) {
var res = parseInt(response.trim());
alert(response);
if (response.trim() == "10") {
$("#errorlog").html("Email and Password is must");
//alert(response);
}
else if (res >= 1) {
//alert(response);
document.getElementById('email').value = "";
document.getElementById('password').value = "";
window.location = "index.php";
}
else {
$("#errorlog").html("E-mail or Password is incorrect");
}
}, error: function (response) {
alert("FAIL");
alert(response);
//alert(response[0]);
//response is json you need to parse it
// var json = response,
// obj = JSON.parse(json);
// alert(response.length);
// alert(response.length);
}
});
return false;
}
</script>
The php code:
<?php
error_reporting(1);
if (!isset($_SESSION)) {
session_start();
}
require_once("../config/encrypt.php");
require_once '../config/functions.inc';
require_once '../config/database.php';
///////////////login check////////////
if ($_POST['login'] == "login") {
echo "fdgdffdf";
if (empty($_POST['password']) or empty($_POST['email'])) {
echo "10";
exit;
} else {
$en = new Encryption();
$password = trim($_POST['password']);
$email = $en->removeBadChars(trim($_POST['email']));
$db = new Database();
if ($db->open())
$password = sha1($password);
{
$sql = "select * from phpap105_signup where email='$email' and password='$password'";
// echo "select * from phpap105_signup where email='$email' and password='$password'";
//exit;
$res = mysqli_query($db->resourse(), $sql);
$cou = mysqli_num_rows($res);
if ($cou >= 1) {
$row = mysqli_fetch_array($res);
$_SESSION['client_user_id'] = $row[0];
$_SESSION['client_user_id1'] = $row[0];
$_SESSION['client_username'] = $row[1];
$_SESSION['client_logged'] = true;
// $_SESSION['adm_status'] = $row['status'];
$r = "success";
} else {
$r = "fail";
}
echo $cou;
// exit;
}
}
echo $r;
}
/////login end/////////////////
?>
Related
I want to send some data from a form to a PHP file using jQuery. I've searched and I noticed I have to send the data as JSON and receive multiple variables as an array. However I'm Completely confused it's not working.
<input id="username" type="text" class="inputBox">
<input id="password" type="password" class="inputBox">
<button id="submitLogin" class="submitLogin">login</button>
<div id="test"></div>
<div id="test1"></div>
$(document).ready(function() {
$("#submitLogin").click(function() {
var superuser = $("#username").val();
var superpass = $("#password").val();
$.ajax({
type: "POST",
url: 'http://localhost/mainclinic/controllers/login/login.php',
dataType: 'application/json',
data: {
loginid: superuser,
loginpass: superpass
},
cache: false,
success: function(result) {
$('#test').html(result[0]);
$('#test1').html(result[1]);
}
})
})
})
<?php
include "../config.php";
if (!$db)
{
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$username = mysqli_real_escape_string($db, $_POST['loginid']);
$password = mysqli_real_escape_string($db, $_POST['loginpass']);
$sql = "SELECT id FROM superusers WHERE docid = '$username' and doccpass = '$password'";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0)
{
$array = array(success, $username);
echo json_encode($array);
}
else
{
$array = array(failed, nousername);
echo json_encode($array);
}
}
?>
Change This section to this:
$.ajax
({
type:"POST",
url:'http://localhost/mainclinic/controllers/login/login.php',
dataType: "json",
data:{loginid:superuser,loginpass:superpass},
cache: false,
success:function (result) {
$('#test').html(result.status);
$('#test1').html(result.result);
}
})
And Php code like this:
if(mysqli_num_rows($result) > 0)
{
$array = array('status' => 'success', 'result' => $username);
echo json_encode($array);
}else
{
$array = array('status' => 'failed', 'result' => 'nousername');
echo json_encode($array);
}
I have a login form using ajax and a php code. The issue is that is always returns an error instead of logging me into the system. I have spent days trying to find the error but I can't.
php :
<?php
include 'db.php';
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$cek = mysqli_query($conn, "SELECT * FROM user_csr WHERE email='$email' AND csr_pwd='$password'");
if(mysqli_num_rows($cek)>0)
{
echo 'true';
}
else
{
echo 'false';
}
?>
ajax :
function ceklogin(){
var email = document.getElementById('mail').value;
var password = document.getElementById('pass').value;
$.ajax({
url: 'tes.php',
method: 'POST',
data: {email: email, password: password},
success: function(html) {
if(html == 'true')
{
alert("login success");
}
else
{
alert("login failed");
}
}
});
}
<form>
<input type="email" name="email" id="mail" required>
<input type="password" name="password" id="pass" required>
<button type="submit" class="w3ls-cart" onclick="ceklogin()">Sign In</button>
</form>
the result of an alert is 'login failed'. but email and passwords are in accordance with the database.Hope anyone can help me out on this one, thanks in advance.
This should work. Just make sure you have a DIV as identified below to show your result.
function ceklogin() {
var email = document.getElementById('mail').value;
var password = document.getElementById('pass').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("resultDiv").innerHTML = this.responseText;
}
};
var sentInfo = "email=" + email + "&password=" + password;
xhttp.open("POST", "YourPHPFileHERE.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(sentInfo);
}
you should try adding "===" in your if condition.
` if(html === 'true')
{
alert("login success");
}
else
{
alert("login failed");
}`
I try to make an authentication using angualrJS and php. I tested it by console.log, when the password is incorrect I get error message, and when the password is correct I don't get anything, in this case, I want to be riderected to other view, how can I do please:
app.js
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'NomClient' : $scope.NomClient,
'mdp' : $scope.mdp
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config)
{
// $window.location.href = '#/admin';
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log('error');
});
}
});
login.php
<?php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "test");
if(count($data) > 0)
{
$NomClient=mysqli_real_escape_string($connect, $data->NomClient);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE NomClient = "'.$NomClient.'" AND mdp= "'.$mdp.'"';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
As you see, I have a comment line in app.js: // $window.location.href = '#/admin'; I put it as comment because when I put it, it redirects me to admin view however the password is incorrect.
Thanks in advance
With AngularJS you can use the $location service
$Location - Documentation
Try using:
$location.path("your new path here")
For an example: please refer to the following answer to another post:
https://stackoverflow.com/a/14387747/7018180
Try this code in login.php
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
$result['code'] = 200;
$result['message'] ='Logged In';
}
else
{
$result['code'] = 603;
$result['message'] ='The username or password are incorrect!';
}
$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring ;
die;
And check result code in js if it is 200 then it will be in succes other wise in error.
Change .success\.error to .then(), Change your code like :
$http.post('http://localhost/deb/login.php', data).then(function(response) {
console.log(response.data);
$window.location.href = '#/admin';
}, function(error) {
console.log('error');
});
.success is a property of $http service so if there would be some value in data variable the $window.location is eventually going to get called.. so to improve that you can use if condition inside $http service which would check the passed username and password with the response that it would get from the service and then in if condition you can redirect it to another page.
app.service('AuthenticationService', function ($http, $window){
this.login = function (username, password) {
return $http({
url: 'http://localhost/deb/login.php',
method: 'POST',
params: {
NomClient : username,
mdp : password
}
})
};
});
app.controller('loginCtrl', function ($scope, $state, $http, $window, AuthenticationService, $remember) {
$scope.submit = function()
{
AuthenticationService.login($scope.NomClient,$scope.mdp)
.then(function(response) {
if (response.data.NomClient == $scope.NomClient && response.data.mdp == $scope.mdp)
{
$state.go('application.home');
}
else {
alert('Credentials do not match our records. Please try again.');
}
})
}
});
and instead of $window.location you can use $state.go functionality of angularJS. It would redirect your page to the specific state that would be mentioned and it would look for that state in route file and would execute that state along with its templateUrl and controller.
Here's properly working code for your question tested properly. if you are still looking for a solution
app.js
app.controller('loginCtrl', function ($scope, $http,$state) {
$scope.submit = function ()
{
$scope.data = {
username: $scope.username,
password: $scope.password
}
$http.post('http://localhost/HTML5Application/public_html/login.php', {serviceData: $scope.data})
.success(function (data) {
alert(data);
$state.go('newState');
})
.error(function (data) {
alert("problem with service call");
});
};
});
login.php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "embroidery");
if (count($data) > 0) {
$username = mysqli_real_escape_string($connect, $data->serviceData->username);
$password = mysqli_real_escape_string($connect, $data->serviceData->password);
$query = 'SELECT * FROM `client` WHERE username = "' . $username . '" AND password= "' . $password . '"';
$q = mysqli_query($connect, $query);
if (mysqli_num_rows($q) > 0) {
$_SESSION["logged_in"] = true;
$_SESSION["name"] = $username;
echo $_SESSION["name"];
} else {
echo 'The username or password are incorrect!';
}
}
?>
login.html
<div class="list list-inset" ng-controller="loginCtrl">
<label class="item item-input">
<input type="text" placeholder="Username" required="" ng-model="username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="password">
</label>
<button class="button button-block button-positive" name="submit" ng-click="submit()">Login</button>
</div>
Thank you all, this is the solution of this question, solved by "Mr_Perfect":
we have just to add a condittion in suceess:
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
if(data.code == 200){
$state.go('admin');
}
})
.error(function(data, status, headers, config, rsult)
{
console.log('error');
});
Thanks to you all
I have this code
---------- index.php ----------
<script>
function validLogin() {
var email=$('#memail').val();
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var password=$('#mpass').val();
var dataString = email='+ email + '&password='+ password;
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
if(result=='correct'){
window.location='/';
} else {
}
}
});
return true;
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
</script>
<div class="login">
<div class="input-group">
<input type="text" id="memail" value="" placeholder="Email" class="memail">
</div>
<div class="input-group">
<input type="password" id="mpass" value="" placeholder="Password" class="mpassword">
</div>
<div class="checkout-submit-section">
<div class="payment-submit">
<div class="order-submit">
<button id="msubmit" type="submit" name="submit_button" class="greenx" style="margin-top:-20px;" onclick="validLogin()">
Login
</button>
</div>
</div>
</div>
</div>
and
------ processed.php ---------
<?php
session_start();
include_once('../db/ds.php');
$message=array();
if(isset($_POST['email']) && !empty($_POST['email'])){
$email = $mysqli->real_escape_string($_POST['email']);
$email= htmlentities($email);
}else{
$message[]='email';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password = $mysqli->real_escape_string($_POST['password']);
$password= htmlentities($password);
}else{
$message[]='password';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
}
}else{
$password=md5($password);
$query = "select * from user where email='$email' and password='$password'";
$res = $mysqli->query($query);
$checkUser = $res->num_rows;
if($checkUser > 0){
$lol = $res->fetch_array(MYSQLI_BOTH);
$iduser = $lol['id'];
$_SESSION['status']=true;
$_SESSION['id']=$iduser;
echo 'correct';
}else{
}
}
}
?>
maybe this code for CSRF, but I do not know how to use them
function createToken()
{
$token= base64_encode( openssl_random_pseudo_bytes(32));
$_SESSION['csrfvalue']=$token;
return $token;
}
function unsetToken()
{
unset($_SESSION['csrfvalue']);
}
function validation()
{
$csrfvalue = isset($_SESSION['csrfvalue']) ? mysql_real_escape_string($_SESSION['csrfvalue']) : '';
if(isset($_POST['csrf_name']))
{
$value_input=$_POST['csrf_name'];
if($value_input==$csrfvalue)
{
unsetToken();
return true;
}else{
unsetToken();
return false;
}
}else{
unsetToken();
return false;
}
}
<input type="hidden" name="csrf_name" value="<?php echo createToken();?>"/>
How to use CSRF without input <form action="" method="post">? Because when I test the security of this code, this code dangerous if not using CSRF.
I've been looking for to several sites , but they all use input form.
1.How to use CSRF in the above code ?
Whether my code is too simple? and could be tricked ? How do I secure it ?
If i use ajax , Whether I have to use CSRF ?
EDIT
--------------- processed.php ----------------
<?php
require '../../db/sessions.php';
require '../../db/ds.php';
require '../../db/error.php';
$user=$row['id'];
$message=array();
if(isset($_POST['emailx']) && !empty($_POST['emailx'])){
$emailx = $mysqli->real_escape_string($_POST['emailx']);
$emailx= htmlentities($emailx);
}else{
$message[]='email';
}
if(isset($_POST['hpx']) && !empty($_POST['hpx'])){
$hpx = $mysqli->real_escape_string($_POST['hpx']);
$hpx= htmlentities($hpx);
}else{
$message[]='hp';
}
if(isset($_POST['namax']) && !empty($_POST['namax'])){
$namax = $mysqli->real_escape_string($_POST['namax']);
$namax= htmlentities($namax);
}else{
$message[]='nama';
}
if(isset($_POST['token']) && !empty($_POST['token'])){
$tokens = $mysqli->real_escape_string($_POST['token']);
}else{
$message[]='email';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
}
}else{
if(validation($tokens, $crsfa)==true) {
$query = "UPDATE user SET email='$emailx', nama='$namax', hp='$hpx' WHERE id='$user'";
$res = $mysqli->query($query);
echo 'OKS';
}else{
echo "Null";
return false;
}
}
?>
--------------- index.php ----------------
<meta name="csrf_token" content="<?php echo createToken();?>">
.
.
.
.
.
<script>
function validUbah() {
var hpx=$('#hp').val();
var emailx=$('#email').val();
var namax=$('#nama').val();
var token=$('[name="csrf_token"]').attr('content');
var dataString = 'hpx='+ hpx + '&emailx='+ emailx + '&namax='+ namax + '&token='+ token;
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
success: function(result){
var result=trim(result);
if(result=='OKS'){
$(".spinner").hide();
$(".spanlogin").show();
$(".spanlogin").html('Berhasil');
$(".nm7").html(namax);
} else {
$(".spinner").hide();
$(".spanlogin").show();
$(".spanlogin").html(result);
return false;
}
}
});
return true;
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
</script>
--------------- sessions.php ---------------------
function unsetToken()
{
unset($crsfa);
createToken();
}
function validation($varians, $crsfa)
{
$csrfvalue = isset($crsfa);
if(isset($varians))
{
$value_input=$varians;
if($value_input==$csrfvalue)
{
unsetToken();
return true;
}else{
unsetToken();
return false;
}
}else{
unsetToken();
return false;
}
}
$crsfa=$_SESSION['csrfvalue'];
if you are implementing anti-CSRF techniques, you should use the token on every post/ajax request.
Maybe you can implement your token as meta-Tag:
<meta name="csrf-token" content="MERvRHE0MmVHcSU9OEUfPHs3JSALZQpcAC1ccBVcZA14KVlxN35xHQ==">
Whatever you do, do NOT use MD5 for hashing passwords.
Use PHP's crypt() or other means for password storage.
Cheers
I get a Failure object Object notice. I have looked at multiple examples and still can't figure out the error. I believe my AJAX is not set up properly. The PHP should be good to go, I have a local database and use jQuery with AJAX to handle the request and the response. The page should redirect to the dashboard.php when I have success with logging in.
Here is the form:
<div class="row">
<div class="col-xs-12 text-center">
<h1 class="text_white bad_login">
Log In Please
</h1>
</div>
<div class="col-xs-12 col-sm-4 col-sm-offset-4">
<form class="text_white" method="post" action="/login.php">
<div class="form-group">
<label for="username">User Name:</label>
<input name="username" type="text" class="form-control" id="username" placeholder="User Name">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input name="password" type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default" id="login" name="login">Log In</button>
</form>
</div>
</div>
Here is the PHP:
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// grab form fields and save as php variables
$username = '';
$password = '';
// if (isset($_POST['name'], $_POST['passphrase'])){
// $username = $_POST['name'];
// echo $username;
//
// $password = $_POST['pass'];
// echo $password;
// }
// else {
// $username = null;
// $password = null;
// }
if (isset($_POST['password'])){
$password = $_POST['password'];
//echo $password;
}
else {
$password = null;
}
if (isset($_POST['username'])){
$username = $_POST['username'];
//echo $username;
}
else {
$username = null;
}
// create query to run on database
$qry = "SELECT username, password FROM user WHERE username='".$username. "' AND password='".$password. "' ";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
// check to see if it is only 1 match and then save that information to the session for later use
if( $num_row == 1 ) {
$_SESSION['username'] = $row['username'];
//echo $_SESSION['username'];
$_SESSION['password'] = $row['password'];
//echo $_SESSION['password'];
}
else {
echo ' FALSE! ';
}
// $result->json_encode($result);
echo json_encode($result);
}
//close the connection
$conn->close();
Here is the AJAX which i believe contains the error:
//jQuery(document).ready(function($){
// $('#login').click(function(event){
// event.preventDefault();
// var username = $('#username').val();
// var password = $('#password').val();
//
// if ( $('#username').val() === '' || $('#password').val() === '') {
// $('.bad_login').text('PLEASE ENTER BOTH USERNAME AND PASSWORD');
// }
//
// $.ajax({
// type: 'POST',
// url: '/ChurchCheckIn/login.php',
// dataType: 'json',
// data: 'username='+username+'&password='+password,
//// data: { username : username, password : password},
// success: function(data){
//// if(data === 'true') {
// window.location='/ChurchCheckIn/dashboard.php';
// console.log('if true.... ' + data);
//// }
//// else {
//// $('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
//// console.log('bad html test for other stuff' + data);
//// }
// },
//// fail: function(data){
//// jQuery.parseJSON(data);
//// console.log('failure' + data);
//// $('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
//// },
//// done: function() {
//// console.log('success' + data);
//// window.location='/ChurchCheckIn/dashboard.php';
//// },
// beforeSend:function() {
// $('.bad_login').text('Loading....');
// }
// });
// return false;
// });
//});
jQuery(document).ready(function ($) {
$('#login').click(function (event) {
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
var response = {};
if ($('#username').val() === '' || $('#password').val() === '') {
$('.bad_login').text('PLEASE ENTER BOTH USERNAME AND PASSWORD');
}
var request = $.ajax({
url: '/ChurchCheckIn/login.php',
type: 'POST',
data: 'username='+username+'&password='+password,
dataType: 'json'
});
request.done(function (data) {
response = $.parseJSON(data);
console.log(response);
if (response.success == 'true') {
console.log('success' + data);
window.location = '/ChurchCheckIn/dashboard.php';
} else {
console.log('data came back false');
}
});
request.fail(function (data) {
console.log('failure' + data);
$('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
});
});
});
I have tried multiple ways, i believe one sends an object and the other expects to receive a string. I don't believe I am way offbase, I even made sure to use the newest practices. mysqli in my php and the newer form of success with my jQuery.
Try using data as Javascript object
var request = $.ajax({
url: '/ChurchCheckIn/login.php',
type: 'POST',
data: {username: username, password: password}
dataType: 'json'
});
if that didn't work, use JSON.stringify around the data object, but it should work because jQuery converts the data object automatically.
I believe in a row:
if (response.success == 'true') {
}
there is no element success try check if response variable is not empty.