запрос ajax не работает с проверкой php - PullRequest
0 голосов
/ 21 сентября 2018

Я хочу использовать 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);
        }
     }
?>

Спасибо.

Ответы [ 2 ]

0 голосов
/ 21 сентября 2018

Во-первых, вам нужно вызвать event.preventDefault(), чтобы предотвратить отправку формы в обычном режиме.

Во-вторых, вам нужно получить значения входов в обработчике событий.Ваш код устанавливает data при загрузке страницы, прежде чем пользователь заполнит форму.

В-третьих, ваш PHP-скрипт проверяет параметр contact-form.Это отправляется, когда вы отправляете форму в обычном режиме, но ваш запрос AJAX не устанавливает ее.Вам нужно добавить его в data или удалить if (isset($_POST['contact-form'])) из PHP (если valid.php никогда не используется ни для чего другого, эта проверка, вероятно, не нужна).

$(function() {
  $('#contact-form').on('submit', function(event) {
    event.preventDefault();
    var data = {
      name: $('#name-contact').val(),
      email: $('#email-contact').val(),
      message: $('#message-contact').val(),
      "contact-form": true
    };
    $.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);
      });
  });
});
0 голосов
/ 21 сентября 2018

Измените тип кнопки на кнопку:

<button id="contact-btn" class="" type="button" name="contact-form">Send</button>

Измените свой js-код, как показано ниже:

$(document).ready(function () {
    $('#contact-btn').click(function(event) {
        var data = {
            name: $('#name-contact').val(),
            email: $('#email-contact').val(),
            message: $('#message-contact').val()
        };
        $.ajax({
            url: 'php/valid.php',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function(response) {
                if (response.status == 'success') {
                        console.log('Success !');
                } else if (response.status == 'error') {
                        console.log('Error !');
                } else
                    console.log("Somthing went wrong....")
            },
            error:function(){
                console.log("error");
              }
        });
    });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...