Answer the question
In order to leave comments, you need to log in
How to implement authorization through AJAX and PHP?
Decided to learn a little php and others like them.
From the authorization form (two fields: login, password) I send data to the php script by serializing the form using jQuery.ajax. In response, I expect to receive 'yes' if there is such a user with such a password, and 'no' if, in fact, there is not, outputting via echo.
The problem is that the script sends back a void. Rearranging echo outputs - sometimes only 'yes', sometimes only 'no'.
Tested with passing directly through the form (adding a submit-button and action='auth.php'), everything is fine - outputs yes/no.
There is a suspicion that js intercepts data earlier / later than the php script responds. Everything runs on localhost, php 5.3.13
Form:
<form id='logform' method='post' action=''>
<div class="close"></div>
<div class="title">Вход</div>
<div class="form_err" style="display:block">Неверный логин или пароль</div>
<div class="form_err err_true" style="display:block">Вы успешно авторизованы!</div>
<input id='login' name='login' type="text" placeholder="Логин" />
<input id='password' name='password' type="password" placeholder="Пароль" />
<button id='log_btn'>Вход</button>
</form>
$('#log_btn').click(function() {
$.ajax({
type: "POST",
url: "log_user.php",
data: $('logform').serialize(),
traditional: true,
success: function(resp) {
if (resp == 'yes') {
alert('yes');
$('#logform .form_err:first').css('display', 'none');
$('.err_true').css('display', 'block');
} else if (resp == 'no') {
alert('no');
$('#logform .form_err:first').css('display', 'block');
} else alert(resp);
},
error: function(resp) {
alert('error');
}
});
return false;
});
<?php
require_once('conn_db.php'); // файл с константами для подключения к бд
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB);
if(isset($_POST['login']) && isset($_POST['password'])) {
$username = $_POST['login'];
$password = $_POST['password'];
if ($stmt = $mysqli->prepare("SELECT count(*) FROM test_table WHERE login=?")) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($count_rec);
$stmt->fetch();
$stmt->close();
}
if ($count_rec == null) {
echo 'no';
//exit();
}
// запрос на получение хэша пароля из таблицы
if ($stmt = $mysqli->prepare("SELECT pass FROM test_table WHERE login=?")) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($corr_pass_hash);
$stmt->fetch();
// сравнение с введенным юзером паролем
$pass_hash = crypt($password, $corr_pass_hash);
if ($corr_pass_hash === $pass_hash) {
echo 'yes';
//exit();
} else {
echo 'no';
//exit();
}
$stmt->close();
}
}
$mysqli->close();
?>
Answer the question
In order to leave comments, you need to log in
Still, PHP users' craving for writing kilometers of code for each meager operation is completely inexplicable :)
Well, all right, on the screen of the code per request, because it is written in the documentation. But as many as two queries to the database, why?
Of course, I understand that everything is incomprehensible in a new area for me. But can you at least think a little about your actions? Is there even the slightest point in doing the first query?
All we need is to get the password from the database and compare it with the entered one.
<?php
// файл с константами для подключения к бд
require_once('conn_db.php');
$db = new safemysql($db_config);
if(isset($_POST['login']) && isset($_POST['password']))
{
// запрос на получение хэша пароля из таблицы
$sql = "SELECT pass FROM test_table WHERE login=?s";
$pass = $db->getOne($sql, $_POST['login']);
// сравнение с введенным юзером паролем
if ($pass === crypt($_POST['password'], $pass))
{
exit('yes');
}
}
echo 'no';
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question