Я хочу использовать ajax
для fadeIn
загрузчика во время проверки PHP и возврата значений из него для отображения сообщений с визуальными эффектами, затем fadeOut
загрузчик после его завершения.Но мне не удалось получить простой возврат из проверки PHP в .done function
.
Может кто-нибудь помочь мне, пожалуйста?
Индекс
<form action="php/valid.php" method="post" id="contact-form">
<input id="name-contact" class="uk-input uk-width-1-1 uk-margin-small" type="text" name="name" placeholder="Name"><br>
<input id="email-contact" class="uk-input uk-width-1-1 uk-margin-small" type="text" name="email" placeholder="Email"><br>
<textarea id="message-contact" class="uk-input uk-textarea uk-width-1-1 uk-margin-small" name="message" placeholder="Message" style="height:200px"></textarea>
<button id="contact-btn" class="uk-margin-small uk-button uk-button-secondary uk-width-1-1" type="submit" name="contact-form">Send</button>
</form>
JS
$(function() {
var data = {
name: $('#name-contact').val(),
email: $('#email-contact').val(),
message: $('#message-contact').val()
};
$('#contact-form').on('submit', function(event) {
$.ajax({
url: 'php/valid.php',
type: 'POST',
dataType: 'json',
data: data
})
.done(function(data) {
if (data.status == 'success') {
console.log('Success !');
} else if (data.status == 'error') {
console.log('Error !');
}
})
.fail(function(error) {
console.log(error);
});
});
});
PHP-файл
<?
header('Content-Type: application/json');
$error = false;
$regex_name = '#^[\w\s\p{L}-]{2,30}$#iu';
$regex_message = '#^[\s\S]{3,800}$#i';
if (isset($_POST['contact-form'])) {
$name = $_POST['name'];
$from = $_POST['email'];
$message = nl2br($_POST['message']);
if (!empty($name) && !empty($from) && !empty($message)) {
if (preg_match($regex_name, $name) && filter_var($from, FILTER_VALIDATE_EMAIL) && preg_match($regex_message, $message)) {
$error = array('type' => 'success');
} else {
$error = array('type' => 'error', 'value' => 'There are some errors, please check your informations.');
}
} else {
$error = array('type' => 'error', 'value' => 'Some fields are empty, please check your informations.');
}
}
if (isset($error['type']) && $error['type'] == 'success') {
$return_status['status'] = 'success';
echo json_encode($return_status);
}
else {
if (isset($error['type']) && $error['type'] == 'error') {
$return_status['status'] = 'error';
echo json_encode($return_status);
}
}
?>
Спасибо.