Hi Team
I am having an issue with my signin form its not redirecting to the login and from the login. When signing using correct details its not, but remain on the login page instead of shopping page. What am missing here?
What I have tried:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ecommerce_store";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['email']) && isset($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM users WHERE email = :email");
$stmt->bindParam(':email', $email);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
if (password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
header("Location: shopping.php");
exit();
} else {
$_SESSION['login_error'] = 'Invalid email or password.';
header("Location: login.php");
exit();
}
} else {
$_SESSION['login_error'] = 'Invalid email or password.';
header("Location: login.php");
exit();
}
}
} catch(PDOException $e) {
error_log("Error: " . $e->getMessage());
$_SESSION['login_error'] = 'Error logging in. Please try again later.';
header("Location: login.php");
exit();
}
?>
// js file
<pre>$(document).ready(function() {
$('#cart-badge-btn').click(function(e) {
e.preventDefault();
$('#loginModal').modal('show');
});
$('#loginForm').submit(function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'login.php',
data: formData,
success: function(response) {
if (response === 'success') {
window.location.href = 'shopping.php';
} else {
$('#login-error-message').text('Invalid credentials. Please try again.');
}
},
error: function(xhr, status, error) {
alert('An error occurred while logging in.');
console.log(xhr.responseText);
}
});
});
});
// html code
<pre><!--
<div class="modal" id="loginModal">
<div class="modal-dialog">
<div class="modal-content">
<!--
<div class="modal-header">
<h5 class="modal-title">Login</h5>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<!--
<form id="loginForm" method="POST" action="login.php">
<!--
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
</div>