简体   繁体   English

请求ajax不适用于php验证

[英]request ajax doesn't work with php validation

I want to use ajax in order to fadeIn a loader during PHP validation and returning the values from it to show visual effect messages, then fadeOut the loader when it finishes. 我想使用ajax来在PHP验证期间fadeIn加载器,并从中返回值以显示视觉效果消息,然后在完成时fadeOut加载器。 But I did not managed to get a simple return from PHP validation in the .done function . 但是我没有设法从.done function中的PHP验证中获得简单的回报。

Can anyone help me please? 谁能帮我吗?

Index 指数

<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 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 file 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);
        }
     }
?>

Thank you. 谢谢。

First, you need to call event.preventDefault() to prevent the form from being submitted normally. 首先,您需要调用event.preventDefault()以防止表单正常提交。

Second, you need to get the values of the inputs in the event handler. 其次,您需要获取事件处理程序中输入的值。 Your code is setting data when the page is loaded, before the user has filled in the form. 您的代码正在设置页面加载时(在用户填写表格之前)的data

Third, your PHP script checks for the contact-form parameter. 第三,您的PHP脚本检查contact-form参数。 This is sent when you submit the form normally, but your AJAX request isn't setting it. 当您正常提交表单时发送此消息,但您的AJAX请求未设置它。 You need to add it to data , or remove if (isset($_POST['contact-form'])) from the PHP (if valid.php is never used for anything else, this check is probably not necessary). 您需要将其添加到data ,或从PHP中删除if (isset($_POST['contact-form'])) (如果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); }); }); }); 

Change button type to button: 将按钮类型更改为按钮:

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

Change your js code like below : 更改您的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");
              }
        });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM