AJAX форма подписки на новости сайта
03 Jul 2017
local_offer
html
local_offer
jquery
В качестве парковочной страницы использовал простенький шаблон Eventually.
Минимальная форма подписки на новости сайта:
...
<!-- Форма подписки -->
<form id="signup-form" method="post" action="#">
<input type="email" name="email" id="email" placeholder="Email адрес" required />
<input type="submit" value="Подписаться" />
</form>
<!-- Здесь выведем сообщение пользователю -->
<div id="results"></div>
...
<!-- Подключаем jquery и основной скрипт страницы -->
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script src="assets/js/main.js"></script>
Обработчик формы на javascript (фрагмент main.js):
// Signup Form.
(function() {
// Vars.
var $form = document.querySelectorAll('#signup-form')[0],
$submit = document.querySelectorAll('#signup-form input[type="submit"]')[0],
$message;
// Bail if addEventListener isn't supported.
if (!('addEventListener' in $form))
return;
// Message.
$message = document.createElement('span');
$message.classList.add('message');
$form.appendChild($message);
$message._show = function(type, text) {
$message.innerHTML = text;
$message.classList.add(type);
$message.classList.add('visible');
window.setTimeout(function() {
$message._hide();
}, 3000);
};
$message._hide = function() {
$message.classList.remove('visible');
};
// Events.
// Note: If you're *not* using AJAX, get rid of this event listener.
$form.addEventListener('submit', function(event) {
event.stopPropagation();
event.preventDefault();
// Hide message.
$message._hide();
// Disable submit.
$submit.disabled = true;
// Process form.
// Note: Doesn't actually do anything yet (other than report back with a "thank you"),
// but there's enough here to piece together a working AJAX submission call that does.
window.setTimeout(function() {
//Отправка сообщения
var msg = $('#signup-form').serialize();
$.ajax({
type: 'POST',
url: 'assets/subscribe.php',
data: msg,
success: function(data) {
$('#results').html(data);
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
});
// Reset form.
$form.reset();
// Enable submit.
$submit.disabled = false;
// Show message.
$message._show('success', 'Спасибо!');
//$message._show('failure', 'Something went wrong. Please try again.');
}, 750);
});
})();
В этом PHP скрипте assets/subscribe.php принимаются и обрабатываются данные:
<?php
//Здесь должны выполнятся какие то действия по добавлению email в БД рассылки новостей
//Пример взят здесь: http://www.php.su/articles/?cat=examples&page=042
$pemail = htmlspecialchars($_POST["email"]);
$file = "maillist.txt";
//error_reporting(0); // запрещаем вывод сообщений о возможных ошибках
//Функция, проверяющая реальность адреса
function test_mail($char) {
$flag = false;
if(eregi("^[_\.0-9a-z-]+@([0-9a-z][-0-9a-z\.]+)\.([a-z]{2,3}$)", $char)) $flag = true;
if ($flag) {
return true;
} else {
return false;
}
}
$email = trim(strtolower($pemail));
//Проверяем, есть ли такой адрес в базе
function copy_mail($char) {
$file = "maillist.txt";
$list = file($file);
for ($i = 0; $i < sizeof ($list); $i++)
if ($char == trim($list[$i])) $flag = true;
if ($flag) {
return true;
} else {
return false;
}
}
//Ппроверяем адрес вышеописаными функциями
if (is_file($file)) {
if (!$email == '') {
if (test_mail($email)) {
if (!copy_mail($email)) {
$temail = "\n$email";
//Добавляем новый email в файл
file_put_contents($file, $temail.PHP_EOL, FILE_APPEND | LOCK_EX);
//Выводим сообщение пользователю
echo 'Ваш email <b>'. $email .'</b> добавлен в список рассылки новостей.';
} else {
echo 'Ваш email <b>'. $email .'</b> уже есть в списке рассылки.';
}
} else {
echo 'Ваш email <b>'. $email .'</b> не существует.';
}
} else {
//Переменная $email по каким то причинам пустая
}
}
?>
Моя парковочная страница: satin-pl.com