I’ve asked the chatgpt, and wacthed all the youtube videos, I think the code is fine but why the ajax didnt send any responses.
in my script js file:
$('#loginForm').submit(function (e) {
e.preventDefault();
// var formData = new FormData(document.getElementById("loginForm"));
$.ajax({
type: "POST",
url: "loginHandle.php",
data: $('#loginForm').serialize(),
// processData: false,
// contentType: false,
dataType: "json",
success: function (response) {
console.log("Response received:", response);
if (response.status == 422) {
$("#errorMessage").text(response.errors);
// document.getElementById("errorMessage").textContent = response.errors;
console.log(response.errors);
} else if (response.status == 200) {
window.location.href = "index.php";
}
},
});
});
in my loginHandle php:
<?php
require_once("sql_connection.php");
$database = new SQLConnect();
$query = $database->connect();
$error = array();
$status = 400;
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login-request'])) {
$email = $_POST['email'];
$checkEmail = $query->prepare("SELECT * FROM `người dùng` WHERE `Email` = :email");
$checkEmail->bindParam(':email', $email);
$checkEmail->execute();
if ($checkEmail->rowCount() == 0) {
$error['email'] = "Email không tồn tại !";
$status = 422;
} else {
$user = $checkEmail->fetch();
if (!password_verify($_POST['password'], $user['Mật khẩu'])) {
$error['password'] = "Mật khẩu không đúng !";
$status = 422;
}
}
if (!$error) {
session_start();
$_SESSION['user_id'] = $user['Mã người dùng'];
// if ($user['Phân loại'] == "Quản trị viên")
// header("location:admin/admin.php");
// else
// header("location:index.php");
$status = 200;
$error = '';
}
// header('Content-Type: application/json');
$response = ['status' => $status, 'errors' => $error];
echo json_encode($response);
}
The ajax had loaded the php file, and it sent 200 ok, but the response is empty.
New contributor
Quoc Anh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2