通过Ajax将HTML表单选择选项发送到PHP验证

通过Ajax将HTML表单选择选项发送到PHP验证

本文介绍了通过Ajax将HTML表单选择选项发送到PHP验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将表单发送到php进行验证,然后再将数据插入到mySQL中.我正在尝试使用AJAX来做到这一点.发送<select> <option>时无法通过验证过程.如果删除<select <option>的验证,则表单将按预期进行处理.通过AJAX发送时,我在控制台中收到以下响应:

I'm trying to send a form to php for validation before inserting data into mySQL. I'm trying to use AJAX to do it. I am unable to get through the validation process when sending a <select> <option>. If I remove the validation for the <select <option> the form processes as expected. When sending via AJAX I get the following response in console:

当我通过不使用AJAX进行发送来处理表单时,验证工作正常.下面是我的代码:

When I process the form by just sending it without AJAX, the validation works fine. Below is my code:

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Validate SelectWith Ajax</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form id="frm" action="process.php" method="post" novalidate>
            <label for="yourOptions">Your Options</label>
            <select id="yourOptions" name="yourOptions" required>
                <option value="" hidden selected>Select One</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
                <option value="4">Option 4</option>
                <option value="5">Option 5</option>
            </select>
            <input type="submit" value="Submit" name="Submit">
            <?php echo "hello"; ?>
        </form>
        <script
            src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous">
        </script>
        <script src="ajax.js"></script>
    </body>
</html>

PHP

<?php

$errors = array();
$data = array();

if($_SERVER["REQUEST_METHOD"] === "POST") {

    if($_POST["yourOptions"] == "") {
        $errors["yourOptions"] = "Please Select One";
    }

    if(!empty($errors)) {
        $data["success"] = false;
        $data["errors"] = $errors;

    } else {
        $data["success"] = true;
        $data["message"] = "Success!";

    }
    echo json_encode($data);
}
?>

jquery AJAX

alert("loaded");
$(document).ready(function() {

    $("#frm").submit(function(event) {
        alert("sub");
        event.preventDefault();

        console.log(typeof document.getElementById("yourOptions"));

        $(".form-group").removeClass("is-invalid");
        $(".text-muted").remove();

        var formData = {
            "yourOptions"       : $("input[name=yourOptions]").val()
        };

        $.ajax({
            type        : "POST",
            url         : "process.php",
            data        : formData,
            dataType    : "json",
            encode      : true
        })

        .done(function(data) {

            console.log(data);

            if(!data.success) {

                if(data.errors.yourOptions) {
                    $("#yourOptions").addClass("is-invalid");
                    $("#frm").append("<span class='text-muted'>" + data.errors.yourOptions + "</span>");
                }

            } else {
                $("form").append("<span class='alert alert-success'>" + data.message + "</span>");
            }
        })
        .fail(function(data) {
            alert("failed");
            console.log;
        });
    });
});

数据类型是对象,但是其他字段也是.如何获取php处理所选选项?

The data-type is object, but then again, so were the other fields. How do I get php to process the selected option?

推荐答案

序列化ajax将发布您想要的所有数据

Serialize ajax will post all data you want

$(document).ready(function(){
    $('#frm').submit(function(event){
    event.preventDefault();
    var formValues = $(this).serialize();
        $.ajax({
        url:"process.php",
        method:"POST",
        data:formValues,
        dataType:"JSON",
            success:function(data){
                if(data === 'ok'){
                    $('#result').html(data);
                } else {
                    $('#result').html(data);
                    $('#frm')[0].reset();
                }
            }
        });
    });
});

您如何显示结果:

<div id="result"></div>

有关详细说明和更多信息,请参见此问题:表单成功后,jQuery ajax setTimeout无法重定向?

See this question for detailed explanition and more : Jquery ajax setTimeout after form succes not redirecting?

这篇关于通过Ajax将HTML表单选择选项发送到PHP验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 07:42