Я создаю функцию входа в систему на своем веб-сайте, и пользователю необходимо запустить модал начальной загрузки для входа в систему.Но когда пользователь вводит неправильное имя или пароль, он будет перенаправлять на другую страницу сообщение об ошибке.Я хочу отобразить сообщение об ошибке в модале вместо того, чтобы перейти на другую страницу.Я видел пример использования ajax.Тем не менее, я новичок в jquery, я не знаю, что я должен включить, чтобы выполнить проверку входа в AJAX.
// модальный
<div class="modal fade" id="modalLoginForm" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content bg-light">
<div class="modal-header bg-dark">
<h4 class="col-12 text-center text-white comp ">Sign in</h4>
</div>
<div class="modal-body mx-3">
<form action="authentication.php" method="post">
<div class="md-form mb-5">
<i class="fas fa-envelope prefix grey-text"></i>
<label data-error="wrong" data-success="right" for="defaultForm-
email">Username:</label>
<input type="text" name="username" class="form-control validate">
</div>
<div class="md-form mb-4">
<i class="fas fa-lock prefix grey-text"></i>
<label data-error="wrong" data-success="right" for="defaultForm-
pass">Password:</label>
<input type="password" name="password" class="form-control validate">
</div>
<form>
</div>
<div class="modal-footer d-flex justify-content-center bg-primary">
<button type="submit" class="btn btn-default text-white
comp">Login</button>
</div>
</div>
</div>
</div>
// php
<?php
session_start()
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'test';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and
display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());}
// Now we check if the data from the login form was submitted, isset()
will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Please fill both the username and password field!');}
// Prepare our SQL, preparing the SQL statement will prevent SQL
injection.
if ($stmt = $con->prepare('SELECT id, password FROM player WHERE name =
?')) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case
the username is a string so we use "s"
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
// Store the result so we can check if the account exists in the
database.
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to
store the hashed passwords.
if ($_POST['password'] === $password) {
// Verification success! User has loggedin!
// Create sessions so we know the user is logged in, they
basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
}
\ js (только концепция)
function login(){
if(validationLogin()){
$.ajax({
url: "authentication.php",
type: "POST",
data: {"username": user,
"password": password,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "OK"){
window.location.href = "home.php",
}else{
window.location.href = "squad.php",
}
}
});
}else{
alert("Incorrect data");
}}
Я хочу разрешитьсообщение об ошибке, которое будет показано в форме.Спасибо за вашу помощь.
<a href="" class="btn btn-secondary btn-rounded login" data-
toggle="modal"
data-target="#modalLoginForm">Login</a>
<div class="login-container"></div>
// js
$('a.login').click(function(event) {
var url = "userlogin.php";
$('.login-container').load(url,function(result){
$('#modalLoginForm').modal({show:true});
});
});
// новый php файл
<script type="text/javascript">
$('#loginForm').on('submit', function( event ) {
// prevent the default submit
event.preventDefault();
var form = $(this);
$.ajax({
url: "authentication.php",
type: "POST",
// use the forms data
data: form.serialize(),
beforeSend: function() {
console.log( "Processing..." );
},
success: function( response ){
// do sth with the response
if(response == "OK") {
// credentials verified
// redirect
location.reload();
}else{
// credentials incorrect
// append errormessage to modal
form.closest('.modal-body').append('<div class="error text-
danger">*'+response+'</div>');
}
},
error: function( response ) {
console.log(response);
}
});
return false;
});
</script>
<div class="modal fade" id="modalLoginForm" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content bg-light">
<div class="modal-header bg-dark">
<h4 class="col-12 text-center text-white comp ">Sign in</h4>
</div>
<div class="modal-body mx-3">
<form action="authentication.php" method="post">
<div class="md-form mb-5">
<i class="fas fa-envelope prefix grey-text"></i>
<label data-error="wrong" data-success="right" for="defaultForm-
email">Username:</label>
<input type="text" name="username" class="form-control validate">
</div>
<div class="md-form mb-4">
<i class="fas fa-lock prefix grey-text"></i>
<label data-error="wrong" data-success="right" for="defaultForm-
pass">Password:</label>
<input type="password" name="password" class="form-control validate">
</div>
<form>
</div>
<div class="modal-footer d-flex justify-content-center bg-primary">
<button type="submit" class="btn btn-default text-white
comp">Login</button>
</div>
</div>
</div>
</div>