带验证的ajax表单提交前端+PHP源码

带验证的表单提交

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Form with Addition CAPTCHA</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .error-message {
            color: red;
            margin-top: 10px;
        }

        .success-message {
            color: green;
            margin-top: 10px;
        }

        body,
        form {
            width: 100%;
            border: none;
            margin: 0;
            padding: 0;
        }

        .main-from {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            justify-content: space-between;
        }

        .item {
            width: 48%;
            line-height: 36px;
        }

        .item input {
            border: 1px silver solid;
        }

        .item-yz { display: flex;
            flex-wrap: flex nowrap;
        }
        .item-yz * { margin: 0 20px;}
        .item-yz input[type=text] {
            max-width: 156px;
            border: silver 1px solid;
        }

        #sub_txt {
            width: 100%;
        }

        button,
        input,
        select,
        textarea {
            font-size: 100%;
            vertical-align: baseline;
            width: 100%;
        }

        button,
        input {
            line-height: normal
        }

        button,
        html input[type=button],
        input[type=reset],
        input[type=submit] {
            border-radius: 10px;
            border: 0;
            background: #215DB8;
            cursor: pointer;
            -webkit-appearance: button;
            color: #FFF
        }

        button:active,
        button:focus,
        button:hover,
        html input[type=button]:active,
        html input[type=button]:focus,
        html input[type=button]:hover,
        input[type=reset]:active,
        input[type=reset]:focus,
        input[type=reset]:hover,
        input[type=submit]:active,
        input[type=submit]:focus,
        input[type=submit]:hover {
            background: #025099
        }

        .button {
            padding: 10px 20px;
            cursor: pointer;
        }


        button::-moz-focus-inner,
        input::-moz-focus-inner {
            border: 0;
            padding: 0
        }

        input[type=text],
        input[type=email],
        input[type=url],
        input[type=password],
        input[type=tel],
        input[type=search],
        textarea {
            background: #fff;
            color: #666;
            border-radius: 3px;
            -moz-box-sizing: border-box;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }

        input[type=text]:focus,
        input[type=email]:focus,
        input[type=url]:focus,
        input[type=password]:focus,
        input[type=tel]:focus,
        input[type=search]:focus,
        textarea:focus {
            color: #111;
            background: #FFF
        }

        input[type=file] {
            max-width: 100%;
            -moz-box-sizing: border-box;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }


        .contact_form input::-webkit-input-placeholder,
        .contact_form textarea::-webkit-input-placeholder,
        .contact_form input::-moz-placeholder,
        .contact_form input:-moz-placeholder,
        .contact_form input:-ms-input-placeholder {
            color: #0d0000;
        }
    </style>

</head>

<body>


    <form id="lyform" name="form" onsubmit="return check(this)">
        <div class="main-from">
            <div class="item">
                <input type="text" maxlength="25" name="name" class="fl" placeholder="Your Name">
            </div>

            <div class="item">
                <input type="text" maxlength="25" name="email" class="fr" placeholder="Your E-mail(*)">
            </div>
            <div class="item">
                <input type="text" maxlength="20" name="phone" class="fl" placeholder="Your WhatsApp">
            </div>
            <!--    <div class="item">
        <input type="text" name="country" class="fr" placeholder="Your Country/Region" />
       </div> -->
            <div class="item">
                <input type="text" maxlength="25" name="company" class="fl" placeholder="Your Company">
            </div>
            <!--        <div class="item">
        <input type="text" name="capacity" class="fr" placeholder="Capacity" />
       </div> -->

            <div id="sub_txt" class="item">
                <textarea name="content" cols="40" rows="10" maxlength="500" aria-required="true" aria-invalid="false"
                    placeholder="Your Message: (*)Tips,Please tell us your detailed needs, such as machine names, capacities, etc."></textarea>
            </div>

        </div>
        <!-- <mainform> -->
        <div class="item-yz">
            <div><span id="num1"></span> + <span id="num2"></span> = ? </div>
            <input type="text" id="captchaInput" placeholder="verification code" required>
        </div>

        <div class="error-message" id="errorMessage"></div>
        <div class="success-message" id="successMessage"></div>



        <div class="form-submit">
            <button type="button" id="submitButton">提交</button>
        </div>
        <div class="item-s"> <input type="radio" name=" " checked="checked"> <span class="wpcf7-list-item-label">We
                value your privacy.I have read and agree to the YunDa <a href="/privacy-policy/">Privacy Policy *.</a>
                (Don't write websites and link.)</span>
        </div>
        <input type="hidden" name="lang" value="en">
        <input type="hidden" name="ip" value=" ">
        <input type="hidden" name="fdtitle" value=" ">
        <input type="hidden" name="id" value="6liuyan">

    </form>



    <script>
        $(document).ready(function () {
            // 生成两个随机数用于验证码
            var num1 = Math.floor(Math.random() * 10);
            var num2 = Math.floor(Math.random() * 10);
            $('#num1').text(num1);
            $('#num2').text(num2);

            $('#submitButton').on('click', function () {
                // 执行验证
                var isValid = validateForm(num1, num2);


                if (isValid) {
                    // 如果验证成功,隐藏错误消息
                    $('#errorMessage').text('');
                    // 执行 AJAX 请求

                    $.ajax({
                        url: "submit.php",
                        type: "POST",
                        data: $('#lyform').serialize(),
                        success: function (data) {

                            $('#successMessage').html(data);
                        },
                        error: function (data) {
                            $('#errorMessage').html('Error: ' + error);
                        }
                    });

                } else {
                    // 如果验证失败,显示错误消息并清空成功消息
                    $('#errorMessage').text('The verification failed. Please try again.').show();
                    $('#successMessage').hide();
                }
            });

            function validateForm(num1, num2) {
                var captchaInput = $('#captchaInput').val();
                var correctResult = num1 + num2;

                // 检查验证码字段是否为空
                if (captchaInput === '') {
                    // 验证失败
                    return false;
                }

                // 验证验证码输入是否正确
                if (parseInt(captchaInput) !== correctResult) {
                    // 验证失败
                    return false;
                }

                // 验证成功
                return true;
            }





        });
    </script>

</body>

</html>

PHP 接收数据。做了一些格式验证


<?php

header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:OPTIONS, GET, POST'); // 允许option,get,post请求
header('Access-Control-Allow-Headers:*');
// header('Access-Control-Allow-Headers:x-requested-with, content-type'); // 允许x-requested-with请求头

$url_referer = isset($_REQUEST['referer']) ? $_REQUEST['referer'] : '';
$http_referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

header('Content-Type: text/html; charset=UTF-8');
?> 

 
</head> 
 

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $title = isset($_POST['title']) ? $_POST['title'] : null;
  $username = isset($_POST['name']) ? $_POST['name'] : null;
  $useremail = isset($_POST['email']) ? $_POST['email'] : null;
  $userinquiry = isset($_POST['content']) ? $_POST['content'] : null;
  $userphone = isset($_POST['phone']) ? $_POST['phone'] : null;
  $usercountry = isset($_POST['country']) ? $_POST['country'] : null;
  $useraddress = isset($_POST['address']) ? $_POST['address'] : null;
  $fromcompany = isset($_POST['from_company']) ? $_POST['from_company'] : null;
  $company = isset($_POST['company']) ? $_POST['company'] : null;

  $materials = isset($_POST['materials']) ? $_POST['materials'] : null;
  $application = isset($_POST['application']) ? $_POST['application'] : null;
  $capacity = isset($_POST['capacity']) ? $_POST['capacity'] : null;
  $products = isset($_POST['products']) ? $_POST['products'] : null;
  $useplace = isset($_POST['useplace']) ? $_POST['useplace'] : null;

  $imtype = isset($_POST['imtype']) ? $_POST['imtype'] : null;
  $imvalue = isset($_POST['imvalue']) ? $_POST['imvalue'] : null;

  $timezone_offset = isset($_POST['timezone_offset']) ? $_POST['timezone_offset'] : null;

  $id = isset($_POST['id']) ? $_POST['id'] : null;

  $servertime = date('Y年m月d日 H:i:s'); //date("Y-m-d" H:i:s); date('Y年m月d日 H:i:s');

  //额外的字段可以在这儿添加
  $metadata = array(
    'materials' => $materials,
    'application' => $application,
    'capacity' => $capacity,
    'products' => $products,
    'useplace' => $useplace,
    'imtype' => $imtype,
    'imvalue' => $imvalue,
    'company' => $company,
    'timezone_offset' => $timezone_offset
  );

};




$ip = $_SERVER['REMOTE_ADDR'] . "-" . $_SERVER['HTTP_X_FORWARDED_FOR'] . "<br>" . $_SERVER['HTTP_CLIENT_IP'];




//$title, $username, $useremail, $userinquiry, $userphone, $usercountry, $useraddress, $fromcompany,  date('Y-m-d H:i:s') ."<hr><br>". 
$string = "name:" . $username . "<Br>E-mail:" . $useremail . "<Br> inquiry:" . $userinquiry . "<Br> company:" . $company . "<Br> <Br> <Br> <Br> tel/whatsapp:" . $userphone . "<Br> link  " . $http_referer . "<Br> ip  " . $ip;

//echo ("$string");


?>
<!-- 判断字段 -->
<?PHP
$pattern = "/^[\w\-]+(\.[\w\-]+)*@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*(\.[a-zA-Z]{2,})$/";

if (!preg_match($pattern, $useremail )) {
  echo " Please confirm the correct email address" ;
    exit() ;
}  

$iqstr=strlen ($userinquiry) ;  

if 
 ( $iqstr >580 ) 

{ 
echo   "<h3> You are robot, CLOSE</h3>"; 
 
exit() ;
} 

if($iqstr <=0 )  //开始判断是够为空  
{ 
echo "<h3> input message <br> "; 
 
exit() ;
} 



?>


<body> 


</body>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值