I am using PHP and Ajax to logging into another page with session variable. When I click submit button nothing happen.
The HTML code are following named as login.php:
<?php
require_once "dbconnection.php";
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: index.php");
exit;
}
?>
<div id='info'> </div>
<form method="POST" class="form-signin" name="mylogin" id="mylogin">
<div class="account-logo">
<img src="assets/img/logo-dark.png" alt="">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="email" name="email" autofocus="" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" id="password" class="form-control">
</div>
<div class="form-group text-right">
Forgot your password?
</div>
<div class="form-group text-center">
<input type="button" value="login" id="login" name="login"
class="btn btn-primary account-btn" >
</div>
<div class="text-center register-link">
Don’t have an account? Register Now
</div>
</form>
In the same page Ajax query is:
<script>
$(document).ready(function (){
$('#mylogin').validate({
rules: {
password:{
required:true;
},
email:{
required:true;
email:true
}
},
messages: {
password:{
required:"Requered"
},
email:"Requered"
},
submitHandler : subform
})
function subform() {
var email = $('#email').val();
var password = $('#password').val();
var data = {
"email": email,
"password": password
$.ajax({
type: "POST",
url: "auth/logging.php", // Url to which the request is send
data: data,
// Type of request to be send, called as method
beforeSend:function () {
$('#info').fadeOut();
$('#login').html('Sending ....');
},
success: function(resp){
if(resp=="ok"){
$('#login').html('Login');
setTimeout('window.location.href="index.php";',4000);
}else{
$('#info').fadeIn(1000,function(){
$('#info').html("<div class='alert alert-danger'>" +resp+ "</div>");
$('#login').html('Login');
})
}
}
})
}
})
</script>
My logging.php would be:
<?php
session_start();
require_once "dbconnection.php";
if (isset($_POST['email'])) {
$email = trim($_POST["email"]);
$pass = trim($_POST["password"]);
$password = md5($pass);
$query = $mysqli->prepare("SELECT * FROM users WHERE email=?");
$query->bind_param("d",$email);
$query->execute();
$query->bind_result($id,$user,$myemail,$mypass);
$query->fetch();
if($mypass==$password){
echo 'ok';
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
}else{
echo 'emai & pass wrog';
}
?>
Any help may appreciated.
It should be s instead of d. It stands for string.
$query->bind_param("s",$email);
Also you should never use MD5 for passwords. Use password_hash()
Related
I'm trying to get a redirect to the home page after a successful login, but I don't know how.
I've already used the sleep function but somehow it doesn't work.
Can someone help me please ?
login.php
`
<?php
include "message.php";
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
if(($_POST["username"] == "admin" && $_POST["password"] == "admin"))
{
echo message::success("Your login was successfully.");
sleep(5);
header("Location: index.php");
} else {
echo message::error("Your entered details are wrong.");
}
} else {
header("HTTP/1.0 404 Not Found");
}
`
index.php
`
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script>
$(document).ready(function(){
$("form").on("submit", function(event){
event.preventDefault();
var formValues= $(this).serialize();
$.post("php/login.php", formValues, function(data){
// Display the returned data in browser
$("#msg").html(data);
});
});
});
</script>
<body class="text-center">
<main class="form-signin w-100 m-auto">
<div id="msg"></div>
<form id="contactForm" method="POST" role="form">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<div class="form-floating">
<input type="username" name="username" class="form-control" id="floatingInput" placeholder="Username">
<label for="floatingInput">Username</label>
</div>
<div class="form-floating">
<input type="password" name="password" class="form-control" id="floatingPassword" placeholder="Password">
<label for="floatingPassword">Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<input type="submit" name="login" class="w-100 btn btn-lg btn-primary">Sign in
<p class="mt-5 mb-3 text-muted">© 2022</p>
</form>
</main>
</body>
`
I've already used the sleep function but somehow it doesn't work
You are using PHP redirect but AJAX requests don't follow response redirects by default. PHP header() will send redirect header, but it be captured by JS. This only works when you load login.php directly from browser.
You need to redirect user using Javascript:
$.post("php/login.php", formValues, function(data){
document.location.href = 'index.php';
});
try this in your PHP file...
<?php
if(($_POST["username"] == "admin" && $_POST["password"] == "admin"))
{
// echo message::success("Your login was successfully."); // uncomment if you want the result to send to frontend
// sleep(5);
header("Location: dashboard.php"); // uncomment if you want to get to your dashboard or index and print the success result there...
} else {
echo message::error("Your entered details are wrong.");
}
or in your javascript file:
$.post("php/login.php", formValues, function(data){
$("#msg").html(data);
setTimeOut(() => {
window.location.href = 'dashboard.php';
}, 2000) //after displaying it will redirect to your dashboard or index
});
You can also get into dashboard.php and print the login success result
view: login.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
elogin = $("#elogin").val();
plogin = $("#plogin").val();
remember_me = $("#remember_me").val();
$.ajax({
type:"POST",
data:{"elogin":elogin,"plogin":plogin,"remember_me":remember_me},
url:"<?php echo base_url(); ?>redirect",
success: function(data) {
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect)
{
window.location.replace(data.redirect);
}
else
{
$(".login_success").html('<p>' + data.error + '</p>');
}
}
});
});
});
</script>
<div class="tab-pane" id="profile" role="tabpanel" data-mh="log-tab">
<div class="title h6">Login to your Account</div>
<form class="content">
<div class="login_success"></div>
<div class="row">
<input class="form-control" placeholder="" type="email" id="elogin">
<input class="form-control" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox">Remember Me
</div>
Login
</div>
</div>
</form>
</div>
controller:
public function login_redirect()
{
$email = $this->input->post('elogin');
$password = $this->input->post('plogin');
$remember = $this->input->post('remember_me');
if($email=='' || $password=='')
{
echo json_encode(array('error' => 'All fields are mandatory. Please fill all details.'));
}
else
{
$this->db->select('*');
$this->db->from('user');
$where = "email='".$email."' and password='".$password."' and status='1'";
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result_array();
$this->session->set_userdata('user_id',$result);
if (!isset($_POST))
{
header ("Location:".base_url()."thankyou");
}
else
{
echo json_encode(array('redirect' => base_url().'thankyou'));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
}
}
In this code, I am creating a login module which works fine. Now, I also want to integrate the remember me option when user check remember me checkbox server ask to want to save detail or not. When user logout it doesn't require to fill it's detailed again inside the login form. Once the user checks on remember me checkbox. So, How can I do this? Please help me.
Thank You
You can make this by using cookie.
try following code:
//php (controller):
//after success login
if($remember){
//set cookie
$this->input->set_cookie('email', $email, 86500);
$this->input->set_cookie('password', $password, 86500);
}else
{
//delete cookie
delete_cookie('email');
delete_cookie('password');
}
view: login.php
//set cookie value if checked remember me.
<div class="row">
<input class="form-control" value="<?php if (get_cookie('email')) { echo get_cookie('email'); } ?>" placeholder="" type="email" id="elogin">
<input class="form-control" value="<?php if (get_cookie('password')) { echo get_cookie('password'); } ?>" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox" <?php if (get_cookie('email')) { ?> checked="checked" <?php } ?>>Remember Me
</div>
You can create the cookie with your javascript when you get the response of your ajax call. You should use document.cookie() if you choose this way to do.
If you choose the server side, CodeIgniter have a Cookie Helper. For use it, you have to add it 'cookie' on your autoload. You can load it with this line too :
$this->load->helper('cookie');
when the helper is loaded, you have to create the cookie in your controller like this :
$this->input->set_cookie('cookie_name', $value, time_in_seconds);
In my app I want to make a login page. I want do do this login using ajax jquery. If login success it navigate to next page or show a error message in a div.
this is my code
<form role="form">
<div class="form-group radio-inline">
<label><b>I Am</b></label>
<input type="radio" name="category" value="s"> Student
<input type="radio" name="category" value="t"> Teacher
<input type="radio" name="category" value="p"> Parent
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email address">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</form>
<div id="error">
</div>
jquery
$(document).on('click','.btn',function() {
var email = $("#email").val();
var password = $("#password").val();
var category = $("input[name=category]:checked").val();
$.ajax({
url: "../logincheck.php",
type: "POST",
data: {category:category,email:email,password:password},
success:function(data) {
if (data==='studentlogin') {
window.location.href = '../student/index.php';
}
if(data==='teacherlogin'){
window.location.href = '../teacher/index.php';
}
if(data==='teachersubject') {
window.location.href = '../teacher/subjectadd.php';
}
else {
window.location.href = 'login.html';
$("#error").html("Invalis Email/Password");
}
}
});
});
logincheck.php
$category=$_POST['category'];
$email=$_POST['email'];
$pwd=$_POST['password'];
if ($category == 's') {
$result=mysqli_query($conn,"SELECT studentid,studentfname FROM studentinfo WHERE emailid='$email' and pwd='$pwd'");
$res=mysqli_fetch_array($result);
if($res[0]>0){
$_SESSION['snstudentid']=$res[0] ;
$_SESSION['snstudentfname']=$res[1] ;
echo "studentlogin";
//header("location:student/index.php");
exit();
}
else{
echo "error";
//header("location:pages/login.html");
}
} elseif ($category == 't') {
$result=mysqli_query($conn,"SELECT teacherid,teacherfname FROM teacherinfo WHERE emailid='$email' and pwd='$pwd'");
$res=mysqli_fetch_array($result);
if($res[0]>0){
$check_subject = mysqli_query($conn, "SELECT count(teachersubjectid) FROM teachersubject WHERE teacherid='$res[0]'");
$subject_result = mysqli_fetch_array($check_subject);
if ($subject_result[0]>0) {
$_SESSION['snteacherid']=$res[0];
$_SESSION['snteacherfname']=$res[1];
echo "teacherlogin";
//header("location:teacher/index.php");
exit();
} else {
$_SESSION['snteacherid']=$res[0];
$_SESSION['snteacherfname']=$res[1];
echo "teachersubject";
//header("location:teacher/subjectadd.php");
exit();
}
} else{
echo "error";
//header("location:pages/login.html");
}
}
that error message show for few second and then it goes.I do that error class style display:none;
How I do that?Please help me.
Have a look at what this code does:
else {
window.location.href = 'login.html';
$("#error").html("Invalis Email/Password");
}
yes, it redirects the page to login.html, then, while the page is loading it puts up the error message, then the page load completes and, in your initial login page, the error message is empty.
Remove the line:
window.location.href = 'login.html';
assuming you are already on login.html.
If <div id="error"> has a style of display:none;, then its contents will not be displayed. Inside of the ajax success callback, $("#error").html("Invalis Email/Password"); needs to be $("#error").html("Invalis Email/Password").show(); to set display:block;. See .show().
Tried some solutions here however it did not work as expected. The login page keeps refreshing every time I click the Sign In button. My codes as of now:
index.php
<?php include('header.php'); ?>
<body id="login">
<div class="container">
<div class="row-fluid">
<div class="span6"><div class="title_index"><?php include('title_index.php'); ?></div></div>
<div class="span6"><div class="pull-right"><?php include('login_form1.php'); ?></div></div>
</div>
<div class="row-fluid">
<div class="span12"><div class="index-footer"><?php include('link.php'); ?></div></div>
</div>
<?php include('footer.php'); ?>
</div>
<?php include('script.php'); ?>
</body>
</html>
login_form.php
<form id="login_form1" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Sign in</h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="Username" required>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<button data-placement="right" title="Click Here to Sign In" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-signin icon-large"></i> Sign in</button>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').tooltip('show');
$('#signin').tooltip('hide');
});
</script>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#login_form1").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "login.php",
data: formData,
success: function(html){
if(html=='true')
{
$.jGrowl("Loading File Please Wait......", { sticky: true });
$.jGrowl("Welcome to Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'dashboard_teacher.php' }, delay);
}else if (html == 'true_student'){
$.jGrowl("Welcome to Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'student_notification.php' }, delay);
}else
{
$.jGrowl("Please Check your username and Password", { header: 'Login Failed' });
}
}
});
return false;
});
});
</script>
login.php
<?php
include('dbcon.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
/* student */
$conn = mysqli_connect('localhost','root','','capstone');
$result = mysqli_query($conn, "SELECT * FROM student WHERE username='$username' AND password='$password'")or die(mysqli_error($conn));
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
/* teacher */
$conn = mysqli_connect('localhost','root','','capstone');
$query_teacher = mysqli_query($conn, "SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error($conn));
$num_row_teacher = mysqli_num_rows($query_teacher);
$row_teahcer = mysqli_fetch_array($query_teacher);
if( $num_row > 0 )
{
$_SESSION['id']=$row['student_id'];
echo 'true_student';
}
else if ($num_row_teacher > 0)
{
$_SESSION['id']=$row_teahcer['teacher_id'];
echo 'true';
}
else
{
echo 'false';
}
?>
By the way I have two logins, admin and user. The admin login works perfectly fine, while the user login (this one) refreshes always on the login page. I used the same codes for admin. Thanks!
Try changing the <button> to an <input> with type="submit"
You Need to Change code for login_form.php :
<form id="login_form1" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Sign in</h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="Username" required>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<button data-placement="right" title="Click Here to Sign In" id="signin" name="login" class="btn btn-info" type="button"><i class="icon-signin icon-large"></i> Sign in</button>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').tooltip('show');
$('#signin').tooltip('hide');
});
</script> </form> <script>
jQuery(document).ready(function(){
jQuery("#login_form1").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "login.php",
data: formData,
success: function(html){
if(html=='true')
{
$.jGrowl("Loading File Please Wait......", { sticky: true });
$.jGrowl("Welcome to Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'dashboard_teacher.php' }, delay);
}else if (html == 'true_student'){
$.jGrowl("Welcome to Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'student_notification.php' }, delay);
}else
{
$.jGrowl("Please Check your username and Password", { header: 'Login Failed' });
}
}
});
return false;
});
}); </script>
Good afternoon,
I'm looking for some advise on Codeigniter and getting an Ajax login form to work with my controller and upon being successfully logged in then to take me to a dashboard/homescreen for the particular user.
Here is my 'auth.php' Controller code:
class Auth extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('data_model');
$this->load->database();
}
//** Check Status & Redirect To Login **//
public function index() {
if($this->session->userdata('admin_login') == 1)
redirect(base_url() . 'admin/dashboard', 'refresh' );
else if($this->session->userdata('staff_login') == 1)
redirect(base_url() . 'staff/dashboard', 'refresh' );
else if($this->session->userdata('client_login') == 1)
redirect(base_url() . 'client/dashboard', 'refresh' );
$this->load->view('login');
}
//** Login Function **//
function ajax_login() {
$response = array();
//** Credentials of user login **//
$email = $_POST["email"];
$password = $_POST["password"];
$response['submitted_data'] = $_POST;
//** Validating the login **//
$login_status = $this->validate_login($email, $password);
$response['login_status'] = $login_status;
if ($login_status == 'success') {
$response['redirect_url'] = $this->session->userdata('last_page');
}
}
//** Validating Credentials **//
function validate_login($email = '' , $password = '') {
$credentials = array('email' => $email, 'password' => sha1($password));
//** Checking Admin Credentials **//
$query = $this->db->get_where('admin', $credentials);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('admin_login', '1');
$this->session->set_userdata('login_user_id', $row->admin_id);
$this->session->set_userdata('name', $row->name);
$this->session->set_userdata('login_type', 'admin');
return 'success';
}
& here is my login.php view.
<div class="login-container">
<div class="row">
<div class="col-sm-6">
<script type="text/javascript">
jQuery(document).ready(function($)
{
// Reveal Login form
setTimeout(function(){ $(".fade-in-effect").addClass('in'); }, 1);
// Validation and Ajax action
$("form#login").validate({
rules: {
email: {
required: true
},
password: {
required: true
}
},
messages: {
email: {
required: 'Please enter your email.'
},
password: {
required: 'Please enter your password.'
}
},
// Form Processing via AJAX
submitHandler: function(form)
{
$.ajax({
url: "auth/validate_login",
method: 'POST',
dataType: 'json',
data: {
do_login: true,
email: $(form).find('#email').val(),
password: $(form).find('#password').val(),
},
success: function(resp)
{
show_loading_bar({
delay: .5,
pct: 100,
finish: function(){
// Redirect after successful login page (when progress bar reaches 100%)
if(resp.accessGranted)
{
window.location.href = 'auth/index';
}
else
{
toastr.error("You have entered wrong password, please try again. User and password is <strong>demo/demo</strong> :)", "Invalid Login!", opts);
$passwd.select();
}
}
});
}
});
}
});
// Set Form focus
$("form#login .form-group:has(.form-control):first .form-control").focus();
});
</script>
<!-- Errors container -->
<div class="errors-container">
</div>
<!-- Add class "fade-in-effect" for login form effect -->
<form method="post" role="form" id="login" class="login-form fade-in-effect">
<div class="login-header">
<img src="<?php echo base_url();?>assets/images/logo#2x.png" alt="" width="80" />
<span>log in</span>
</a>
<p>Dear user, log in to access your user area!</p>
</div>
<div class="form-group">
<label class="control-label" for="username">Username</label>
<input type="text" class="form-control input-dark" name="email" id="email" placeholder="Email" data-mask="email" />
</div>
<div class="form-group">
<label class="control-label" for="passwd">Password</label>
<input type="password" class="form-control input-dark" name="password" id="password" placeholder="Password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-dark btn-block text-left">
Log In
</button>
</div>
<div class="login-footer">
Forgot your password?
</div>
</form>
From the code above, I have declared a model but this doesn't actually contain any information as I have a get DB within my controller. Hopefully someone could shed some light on this.
Thank you!
Zak Hargreaves.