How to use header with Ajax - javascript

I'm creating a login checker using jQuery and Ajax, i'm calling query.php which verifies the username and password. And if they don't match, an alert will be shown, and if they are correct it will redirect the user to the other page.
The error message works just fine.
The problem is that when i enter correct username and password, the page doesn't redirect.
In my case i'm been redirected twice, from login.php to query.php then to groupes.php or seance.php
query.php
<?php
require('queries/dbsetup.php');
$username = $_POST['username'];
$password = $_POST['password'];
$type = "";
if (empty($username) || empty($password)) { ?>
<script>
sweetAlert("Oops...", "Veuillez remplir tous les champs !", "error");
</script>
<?php
} else {
echo $type;
switch ($_POST['type']) {
case 'etudiant' : $type = 'etudiant';break;
case 'enseignant' :$type = 'enseignant';break;
}
// Check the username and password
$query = "SELECT username FROM ".$type." where username = '".$username."' AND password ='".$password."' ;";
$set = mysqli_query($conn,$query);
$run = mysqli_fetch_array($set);
$id = $run['username'];
// Save the type
$_SESSION['type'] = $type;
if (!empty($id)) {
$_SESSION['user_id'] = $username;
switch ($type) {
case 'etudiant':
header('location: ../groupes.php',true);exit;break;
case 'enseignant':
header('location: ../seance.php',true);exit;break;
}
} else { ?>
<script>
sweetAlert("Oops...", "Le nom d'utilisateur et le mot de passe ne sont pas identique !", "error");
</script>
<?php
}
}
?>
login.php
<form action="query.php" method="post" id="e1" class="">
<h4>Nouvelle seance</h4>
<input name="username" placeholder="Username" type="text" class="form-control">
<input name="password" placeholder="Password" type="password" class="form-control">
<input name="type" placeholder="Type" type="text" class="form-control">
<button id="login">Login</button>
<p id="result"></p>
</form>
login.js
$('#e1').submit(function(){
return false;
});
$('#login').click(function(){
$.post(
$('#e1').attr('action'),
$('#e1 :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});

You can achieve the desired behavior by telling the client to load the new page via javascript.
You can change these lines
switch ($type) {
case 'etudiant':
header('location: ../groupes.php',true);exit;break;
case 'enseignant':
header('location: ../seance.php',true);exit;break;
}
To
switch ($type) {
case 'etudiant':
?>
<script>
window.location = "../groupes.php";
</script>
<?php
exit;
break;
case 'enseignant':
?>
<script>
window.location = "../seance.php";
</script>
<?php
exit;
break;
}

Related

Index.php not opening after login

My login does not go to index.php after loging in, the page just refreshes
i am using MySqli and the database details are in the config file
This is the login.php
<form action="" method="post">
UserName: <input type="text" name="uname"><br>
Password: <input type="text" name="psw1"><br>
<button type="submit" name="submit">Login</button>
</form>
<?php
require 'config1.php';
if(isset($_POST["submit"])){
$uname = $_POST["uname"];
$psw1 = $_POST["psw1"];
$result = mysqli_query($conn, "SELECT * FROM Users WHERE Username = '$uname'");
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) > 0){
if($psw1 == $row["Password"]){
$_SESSION["login"] = true;
$_SESSION["id"] = $row["id"];
header("Location: index.php");
}
else{
echo
"<script> alert('wrong password'); </script>";
}
}
else{
echo
"<script> alert('User not regitered'); </script>";
};
}
?>
This the index.php, hence the page i am supposed to go to after a successful login
`<?php
require 'config1.php';
if(!empty($_SESSION["id"])){
$id = $_SESSION["id"];
$result = mysqli_query($conn, "SELECT * FROM Users WHERE id = $id");
$row = mysqli_fetch_assoc($result);
}
else{
header("Location: login.php");
}
?>
<!DOCTYPE html>
<html>
<body>
<h1>Welcome <?php echo $row["name"]; ?></h1>
Log out
</body>
</html>`
You are emitting html before you execute the header. It does not work that way. You cannot change the page after the browser has received some html, in this case the form. So re-organise it this way.
<?php
require 'config1.php';
if(isset($_POST["submit"])){
$uname = $_POST["uname"];
$psw1 = $_POST["psw1"];
$result = mysqli_query($conn, "SELECT * FROM Users WHERE Username = '$uname'");
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) > 0){
if($psw1 == $row["Password"]){
$_SESSION["login"] = true;
$_SESSION["id"] = $row["id"];
header("Location: index.php");
exit;
}
else{
echo
"<script> alert('wrong password'); </script>";
}
}
else{
echo
"<script> alert('User not regitered'); </script>";
};
}
?>
<form action="" method="post">
UserName: <input type="text" name="uname"><br>
Password: <input type="text" name="psw1"><br>
<button type="submit" name="submit">Login</button>
</form>
Note that there is an exit after the header because you dont want the rest of the file getting executed.
Note
This assumes that config1.php does not echo or emit any html

Opening a .html with window.location

I'm writing a simple login page in Ajax + Jquery
I have an error when I click on the button. And I don't understand why.
Uncaught SyntaxError: Unexpected end of input
At this line
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
There is my code
<?php
session_start();
//si le user a un session de ouverte
/*if(isset($_SESSION['connecté'])){
header('Location : success.html');
die();
}*/
if (isset($_POST['login'])) {
$connection = new mysqli('localhost','root','','monumap');
$email = $connection->real_escape_string($_POST['emailPHP']);
$password = $connection->real_escape_string($_POST['passwordPHP']);
$data = $connection->query("SELECT id FROM users WHERE email = '$email' AND password = '$password'");
if($data->num_rows >= 0) {//tout et ok -> connexion
$_SESSION['connecté'] = '1';
//$_SESSION['email'] = $email;
header('Location:'.$_SESSION['redirectURL']);
exit('<font color = "green">Connexion reussi...</font>');
}else{
exit('<font color = "red">Le Mot de passe / Email est inconnue </font>');
}
//exit($email . " = " . $password);
}
?>
<html>
<head>
<title>Monumap Connexion</title>
</head>
<body>
<form method="post" action="login.php">
<input type="text" id="email" placeholder="Email..."><br>
<input type="password" id="password" placeholder="Mot de passe..."><br>
<input type="submit" value="Log In" id="login">
</form>
<p id = "reponse"></p>
<div class="Bouton">
<?php if($_SESSION['connecté']==1){
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
}
?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#login").on('click', function () {
var email = $("#email").val();
var password = $("#password").val();
if (email == "" || password == "")
alert('vos inputs sont vides');
else {
$.ajax(
{
url: 'login.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password
},
success: function (reponse) {
$("#reponse").html(reponse);
},
dataType: 'text'
}
);
}
});
});
</script>
</body>
</html>
echo '<input type="button" value="connexion" onclick="window.location.assign('."'http://localhost/loginmap/members/success.html'".');")/>';
It's cause you wrote quote character.
You can use this way as well.
echo '<input type="button" value="connexion" onclick="func()"/>';
?>
<script>
function func(){
window.location.assign("http://localhost/loginmap/members/success.html");
}
</script>

My registration form was working perfectly on localhost but now that it is on a c-panel server it doesn't work

This is my code, I really don't know whats wrong does anyone else know? Currently the error that comes up is Oops! Something went wrong. Please try again later. I know that the issue is not a connection issue and is not a permissions issue. I'm really confused about what I've done wrong and have even contacted customer support multiple times and they didn't know what the issue is.
<?php
include ('config.php');
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT username FROM users WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location:Login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>

How to Disable Browser Back Button functionality after click on Logout Button in PHP

I am having trouble with the browser back button.
When the User press Log out it have to destroy the session and cookies. I wrote the following code:
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
</head>
<body>
<form name="loginform" method="post" action="<?php echo __PROJECT_LINK__; ?>/php/login_exec.php">
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label">
<?php
if( isset($_SESSION['ERRMsg_ARR']) && is_array($_SESSION['ERRMsg_ARR']) && count($_SESSION['ERRMsg_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMsg_ARR'] as $msg) {
echo '<span class="label label-warning" style="margin-left: 5px;">',$msg,'</span>';
}
echo '</ul>';
unset($_SESSION['ERRMsg_ARR']);
}
?>
</label>
</div>
<div class="subnav subnav-fixed nav navbar" style="margin-top: 10px; margin-right: 10px; margin-left: 10px;">
<ul class="nav nav-pills">
<li style="margin-top: 10px;">
<span class="label label-default" style="margin-left: 22px;">Username</span>
<input type="text" id="inputUserName" name="username" placeholder="Username" style="margin-left: 5px;">
</li>
<li style="margin-top: 10px;">
<span class="label label-default" style="margin-left: 22px;">Password</span>
<input type="password" id="inputPassword" name="password" placeholder="Password" style="margin-left: 5px;">
</li>
<li style="margin-top: 10px; margin-bottom: 10px;">
</li>
</ul>
</div>
</div>
</div>
<div class="modal-footer">
<!--?php $this->btnLogLogin->Render();?-->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Sign In</button>
</div>
</form>
</body>
</html>
login_exec.php
<?php
//Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
//Include database connection details
require_once('connection.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
if(isset($_POST['username']))
{
//Sanitize the POST values
$username = ($_POST['username']);
$password = ($_POST['password']);
//Input Validations
if($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
//If there are input validations, redirect back to the login form
if($errflag==true) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location:../index.php");
exit();
}
//Create query
$qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result)) {
while($row = mysql_fetch_array($result))
{
if($row['User_Status']=="Active"){
$expire=time()+60*60*24*30; //1month
setcookie("User_id", $row['User_id'], $expire);
$name = $row['full_name'];
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$_SESSION['USER'] = $firstname;
$_SESSION['UID'] = $row['User_id'];
$_SESSION['URights'] = $row['Rights'];
header("location:../welcome.php");
}
else{
$errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}
}
else {
//Login failed
$errmsg_arr[] = 'Username and Password not found';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}else {
die("Query failed");
}
}
?>
welcome.php
<?php include 'qcubed.inc.php'; ?>
<?php
$User_Name = $_SESSION['USER'];
?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome <?php echo $User_Name; ?></h1>
<h2>Info</h2>
<h2>Sign Out</h2>
</body>
</html>
Info.php
<?php include '../../qcubed.inc.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo __PROJECT_TITLE__; ?> - Full Info</title>
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
</head>
<?php
if(isset($_SESSION['UID']) && $_SESSION['UID'] != "")
{
//Task to do
$User_Name = $_SESSION['USER'];
?>
<body>
<h1>Info about <?php echo $User_Name; ?></h1>
<h2>Sign Out</h2>
</body>
<?php
}
else{
//redirect URL
?>
<script>
alert('You must Login first.');
window.location.href='../../index.php';
</script>";
<?php
exit();
}
?>
</html>
logout.php
<?php
//session_write_close();
session_start(); # NOTE THE SESSION START
$expire=time()-60*60*24*30; //1month
if(isset($_COOKIE['User_id'])):
setcookie('User_id', '', $expire, '/');
endif;
unset($_SESSION['UID']);
unset($_SESSION['USER']);
unset($_SESSION['URights']);
unset($_SESSION['UReg']);
$_SESSION = array();
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
session_unset();
session_destroy();
header("location: ../index.php");
exit(); # NOTE THE EXIT
?>
After pressing log out from Info.php , when I press the browser back button it is showing my previous Logined user page and session username in Info.php page,
but if I use the following javascript in head section of every page it disable all the browser back button at the time of login also.
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
I want to disable the browser back button only after the the time of logout.
Please help me.
That became my problem before. On my case i did not disable the back button. what i did is to check the session when the user is logged out. if there has no detected session, redirect the user to log in page or to what page you like the to redirect.. if there is a detected session redirect it to the homepage
rather than disabling the back button, you can add code to every page to see if the user is logged. If they are NOT logged in, redirect to the login page.
You could create a basic class to handle this for you and just create one on every page.
class sessionHandler
{
function __construct($special = NULL)
{
session_set_cookie_params(60 * 60 * 24 * 365); // 1 year
session_start();
// if no user num (empty session) AND this isn't the login page
if (!isset($_SESSION['userID']) && $special != 'LOGIN') {
//send to login page
header("location: login.php");
}
if ($special == 'LOGOUT') {
// This is the logout page, clear the session and
// send the user to the afterLogout page
session_destroy(); // clear session files on server
$_SESSION = Array(); // clear session variable for this session
unset($_SESSION);
// send to login page
header("location: login.php");
}
if ($special == 'LOGIN') {
// This is the login page, see if user is already logged in
// if so, just send them to the afterLogin page
// if not, validate their credentials, and store the USERID
// in the $_SESSION var
if ($this->getUserPermissions($_SESSION['userID'])) {
// send to any page you want
header("location: dashboard.php");
}
}
}
}
Now, on all your pages, put $session = new sessionHandler(); at the top (before anything else is written.
For login and logout pages you'd put:
$session = new sessionHandler('LOGIN');
$session = new sessionHandler('LOGOUT');
Not copy and paste ready, but hopefully that points you in the right direction. :-)
USE THIS CODE in login_exec.php
if($errflag==true) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location:../index.php");
exit();
}
//Create query
$qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result)) {
while($row = mysql_fetch_array($result))
{
if($row['User_Status']=="Active"){
$expire=time()+60*60*24*30; //1month
setcookie("User_id", $row['User_id'], $expire);
$name = $row['full_name'];
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$_SESSION['USER'] = $firstname;
$_SESSION['UID'] = $row['User_id'];
$_SESSION['login']=true; //ADD THIS CODE IN login_exec.php
$_SESSION['URights'] = $row['Rights'];
header("location:../welcome.php");
}
else{
$errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}
}
now add the code top of the info.php
session_start();
$user=$_SESSION['USER'];
if($_session['login']=true && $_session['user']= $user)
{
code of info.php
}
else
{
header(location:index.php);
}
logout.php
<?php
session_start();
unset($_SESSION['USER']);
session_destroy();
header("Location:index.php");
?>
Just add a condition at all the pages which user can access only if he is login:
if(!isset($_SESSION['UID']) || $_SESSION['UID'] == ''){
// redirect to index or login page
}
At last I solved my problem ..... :-)
I use this following code in
logout.php
<html>
<head>
<script type = "text/javascript" >
window.history.forward();
function preventBack() { window.history.forward(1); }
setTimeout("preventBack()", 0);
window.onunload = function () { null };
</script>
</head>
<body onload="preventBack();" onpageshow="if (event.persisted) preventBack();" onunload="">
Please Wait..
<?php
session_start(); # NOTE THE SESSION START
$expire=time()-60*60*24*30; //1month
if(isset($_COOKIE['User_id'])){
setcookie('User_id', '', $expire);
}
unset($_SESSION['UID']);
unset($_SESSION['USER']);
unset($_SESSION['URights']);
unset($_SESSION['UReg']);
$_SESSION = array();
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
session_unset();
session_destroy();
header("Refresh: 2;url=../index.php");
?>
</body>
</html>
Now it's avoid me to use browser back button after logout and destroy the session.
Thank you all for yours valuable support...

Login form using PHP and JQuery to validate login information from MySQL database

I have a login form that uses JQuery and PHP to validate a username and password. I am trying to switch over from extension mysql to mysqli for better practice and am having a lot of trouble. I think the error exists in the JQuery somewhere because I've tested the login.php validation and it works fine.
So here is my code:
index.php:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true'){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
},
beforeSend:function(){
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){ ?>
<a href='logout_script_2.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<form action="login_script_2.php" method="POST">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
<div class="err" id="add_err"><br></div>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$con = mysqli_connect("localhost","root","PW","db") or die("Connection error: " . mysqli_error($con));
if(isset($_POST['submit'])){
$username = $_POST['name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
if($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
echo 'Access granted';
exit();
}
}
else {
echo "*Wrong username or password";
}
$stmt->close();
}
else {
}
$con->close();
?>
logout.php
<?php
session_start();
unset($_SESSION['user_name']);
header('Location: index.php');
?>
All the attempts to run the code give me the error in the JQuery validation "*Wrong username or password". Thanks in advanced!
When logging in using ajax, you are not posting submit, so this line
if(isset($_POST['submit'])){
is never true so your code never executes.
Either change it to
if(isset($_POST['name'])){
or add it to your ajax posted data
data: "submit=true&name="+username+"&pwd="+password,
AJAX is a partial submission. Make sure you're firing it without using a submit button, or return false; inside your click function, at the bottom. I would use <input type='button' id='login_a' />, if it's not a link. Additionally, you are not setting your submit button, like #Sean said, because it's AJAX.

Categories