I have the following HTML
:
<form action="" method="post" class="form-log-in" autocomplete="off" id="ajaxform">
<div class="main-inputs w1-ha db oh left m-b10">
<input name="login" type="text" size="15" maxlength="15" placeholder="Логин" val="" class="input-style b2 w1-ha db left m-b5">
<input name="password" type="password" size="15" maxlength="15" placeholder="Пароль" val="" class="input-style b2 w1-ha db left m-b5">
<button type="submit" name="submit" value="Войти" class="left m-t10 btn green-btn">Войти</button>
</div>
</form>
and I have the following .ajax request:
<script>
$(document).ready(function() { // вся магия после загрузки страницы
$("#ajaxform").submit(function(){ // перехватываем все при событии отправки
var form = $(this); // запишем форму, чтобы потом не было проблем с this
var error = false; // предварительно ошибок нет
form.find('input, textarea').each( function(){ // пробежим по каждому полю в форме
if ($(this).val() == '') { // если находим пустое
alert('Заполните поле "'+$(this).attr('placeholder')+'"!'); // говорим заполняй!
error = true; // ошибка
}
});
if (!error) { // если ошибки нет
var data = form.serialize(); // подготавливаем данные
$.ajax({ // инициализируем ajax запрос
type: 'POST', // отправляем в POST формате, можно GET
url: 'login.php', // путь до обработчика, у нас он лежит в той же папке
dataType: 'json', // ответ ждем в json формате
data: data, // данные для отправки
success: function(data){ // событие после удачного обращения к серверу и получения ответа
if (data['error']) { // если обработчик вернул ошибку
alert(data['error']); // покажем её текст
} else { // если все прошло ок
alert('Вы авторизованы!'); // пишем что все ок
}
},
error: function (xhr, ajaxOptions, thrownError) { // в случае неудачного завершения запроса к серверу
alert(xhr.status); // покажем ответ сервера
alert(thrownError); // и текст ошибки
}
});
}
return false; // вырубаем стандартную отправку формы
});
});
I am just strating to code on PHP, so don't tream me hard on my code: :D
<?php
if($_POST){
session_start();
include_once('other/inc/config.php');
include_once("other/inc/bd.php") or die(mysql_error());
$login = $_POST['login'];
$password = $_POST['password'];
$login = htmlspecialchars(stripslashes(trim($login)));
$password = md5(htmlspecialchars(trim(stripslashes($password))));
$json = array();
if(!$login or !$password) {
$json['error'] = 'Вы ввели не всю информацию, вернитесь назад и заполните все поля!'; // пишем ошибку в массив
echo json_encode($json); // выводим массив ответа
die(); // умираем
}
// подключаемся к базе
// файл bd.php должен быть в той же папке, что и все остальные, если это не так, то просто измените путь
$result = mysql_query("SELECT * FROM users WHERE login = '$login'", $db);
$myrow = mysql_fetch_array($result);
if (!$myrow['password']) {
$json['error'] = 'Извините, введённый вами login или пароль неверный.2121'; // пишем ошибку в массив
echo json_encode($json); // выводим массив ответа
die();
} else {
//если существует, то сверяем пароли
if ($myrow['password'] == $password) {
//если пароли совпадают, то запускаем пользователю сессию! Можете его поздравить, он вошел!
$_SESSION['login'] = $myrow['login'];
$_SESSION['id'] = $myrow['id'];//эти данные очень часто используются, вот их и будет "носить с собой" вошедший пользователь
# json use
$json['error'] = 'Вы успешно зашли!';
echo json_encode($json); // выводим массив ответа
die();
} else {
$json['error'] = 'Извините, введённый вами login или пароль неверный.'; // пишем ошибку в массив
echo json_encode($json); // выводим массив ответа
die();
}
}
$json['error'] = 0; // ошибок не было
echo json_encode($json); // выводим массив ответа
} else {
echo 'Не шали!'; // высылаем
header('Refresh: 0; URL=/');
}
?>
What is not working? I think there are a few problems that need to be fixed;
For example:
So onlick on my form button, I make ajax hook the POST
event and lead to login.php where I check the form and then do what it says inside. But for me, everything seems nice and it should work, and partly, it works, for example if I leave fiels in the form empty, I will receive alert message saying "Please fill in the $var
field". And it even sends me some of the errors via json['error'] = '';
but I tried to look at that line where it gets the error, but in my opinion there is nothing wrong... Please help me to solve that.
Thanks!
You said you should receive a json return type on your ajax call. Doesn't your php have to send only json?
echo 'Не шали!'; // высылаем
header('Refresh: 0; URL=/');
becomes
echo json_encode(array('error' => 'nope'));
?