【问题标题】:Bootstrap modal contact form submission is not working引导模式联系表单提交不起作用
【发布时间】:2018-09-20 08:04:07
【问题描述】:

我确实验证了 Bootstrap 模态联系表。它运行良好。但是提交表单不起作用,它显示了写在代码中的错误消息。我试图找出错误,但它没有发生。请帮助您的想法。

<html>
<head>
<title>Contact Form</title>

<!-- Latest minified bootstrap css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>


<body>

<!--Popup Auto Load -->
<a id="linkval" data-toggle="modal" href="#modalForm"></a>
<!--Popup Auto Load -->



<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Contact Form</h4>
            </div>

            <!-- Modal Body -->
            <div class="modal-body">
                <p class="statusMsg"></p>
                <form role="form">
                    <div class="form-group">
                        <label for="inputName">Name</label>
                        <input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail">Email</label>
                        <input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
                    </div>
                    <div class="form-group">
                        <label for="inputMobile">Mobile Number</label>
                        <input type="text" class="form-control" id="inputMobile" placeholder="Enter your mobile number"/>
                    </div>
                    <div class="form-group">
                        <label for="inputLocation">Area/City Name</label>
                        <input type="text" class="form-control" id="inputLocation" placeholder="Enter your city name"/>
                    </div>
                    <div class="form-group">
                        <label for="inputMessage">Requirement</label>
                        <textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
                    </div>
                </form>
            </div>

            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
            </div>
        </div>
    </div>
</div>

<script>
function submitContactForm(){
    var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    var name = $('#inputName').val();
    var email = $('#inputEmail').val();
    var mobile = $('#inputMobile').val();
    var location = $('#inputLocation').val();
    var message = $('#inputMessage').val();
    if(name.trim() == '' ){
        alert('Please enter your name.');
        $('#inputName').focus();
        return false;
    }else if(email.trim() == '' ){
        alert('Please enter your email.');
        $('#inputEmail').focus();
        return false;
    }else if(email.trim() != '' && !reg.test(email)){
        alert('Please enter valid email.');
        $('#inputEmail').focus();
        return false;
    }else if(mobile.trim() == '' ){
        alert('Please enter your mobile number.');
        $('#inputMobile').focus();
        return false;
    }else if(location.trim() == '' ){
        alert('Please enter your city name.');
        $('#inputLocation').focus();
        return false;           
    }else if(message.trim() == '' ){
        alert('Please enter your message.');
        $('#inputMessage').focus();
        return false;
    }else{
        $.ajax({
            type:'POST',
            url:'submit_form.php',
            data:'contactFrmSubmit=1&name='+name+'&email='+email+'&mobile='+mobile+'&location='+location+'&message='+message,
            beforeSend: function () {
                $('.submitBtn').attr("disabled","disabled");
                $('.modal-body').css('opacity', '.5');
            },
            success:function(msg){
                if(msg == 'ok'){
                    $('#inputName').val('');
                    $('#inputEmail').val('');
                    $('#inputMobile').val('');
                    $('#inputLocation').val('');
                    $('#inputMessage').val('');
                    $('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
                }else{
                    $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
                }
                $('.submitBtn').removeAttr("disabled");
                $('.modal-body').css('opacity', '');
            }
        });
    }
}
</script>


<script type="text/javascript">
    $(document).ready(function() { $('#linkval').click(); });
    //$('#linkval').click();
</script>




</body>
</html>

下面给出了用于提交表单的 PHP 代码。我无法在 JavaScript 和 PHP 中找到错误。 JavaScript 验证是完美的,所以我认为 PHP 代码是错误的原因。

<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['mobile']) && !empty($_POST['location']) && !empty($_POST['message'])){

    // Submitted form data
    $name   = $_POST['name'];
    $email  = $_POST['email'];
    $mobile  = $_POST['mobile'];
    $location  = $_POST['location'];
    $message= $_POST['message'];

    /*
     * Send email to admin
     */
    $to     = 'sample@gmail.com';
    $subject= 'Contact Request Submitted';

    $htmlContent = '
    <h4>Contact request has submitted at Company, details are given below.</h4>
    <table cellspacing="0" style="width: 300px; height: 200px;">
        <tr>
            <th>Name:</th><td>'.$name.'</td>
        </tr>
        <tr style="background-color: #e0e0e0;">
            <th>Email:</th><td>'.$email.'</td>
        </tr>
        <tr>
            <th>Mobile:</th><td>'.$mobile.'</td>
        </tr>
        <tr>
            <th>Location:</th><td>'.$location.'</td>
        </tr>
        <tr>
            <th>Message:</th><td>'.$message.'</td>
        </tr>
    </table>';

    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // Additional headers
    $headers .= 'From: User<sender@example.com>' . "\r\n";

    // Send email
    if(mail($to,$subject,$htmlContent,$headers)){
        $status = 'ok';
    }else{
        $status = 'err';
    }

    // Output status
    echo $status;die;
}

【问题讨论】:

  • 我没有看到或收到任何客户端错误消息。
  • 在PHP文件中删除die;声明并进行检查
  • 另外,die 不应该用括号调用吗?喜欢die();
  • 用 die() 更改后仍然无法正常工作!
  • 去掉die还是一样的问题。

标签: javascript php forms validation


【解决方案1】:

Expect Die() 语句和电子邮件验证条件没有发现任何问题。在你的 php 文件中添加 else 语句,这样如果你的条件不满足 else 语句将返回一些东西。

$status = 'err';
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && !empty($_POST['mobile']) && !empty($_POST['location']) && !empty($_POST['message'])){
//your code
   }else{
echo $status;
}

【讨论】:

  • 尝试提醒msg,以便我们知道返回的结果。基于此,您可以检查 PHP 代码或脚本代码。
  • 已检查,但仍然无法正常工作,并发送错误消息为“发生了一些问题,请重试”,我已在代码中写入。
  • 收到的 msg 参数值是多少?
  • 将您的电子邮件验证码从 (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) 更新为 filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
【解决方案2】:

如果您是初学者,我建议您通过逐个添加元素来实现代码,检查功能并走得更远。这种方式将帮助您更好地分析和调试代码。

因此,问题可能出在 PHP 代码中的 if 语句上。

只需尝试在您的 PHP 代码中首先使用它,然后尝试 javascript 是否命中服务器代码。

if(isset($_POST['contactFrmSubmit'])
{
    echo "ok";
    die();
}

$.ajax中添加error,看看有没有报错。

$.ajax({
type:'POST',
url:'submit_form.php',
data:$('form').serialize()
beforeSend: function () {
},
success:function(msg){
},
error(jqXHR jqXHR, String textStatus, String errorThrown)
{
}
});

为了获得最佳实践,您可以再做一些更改。

首先,在javascript中尝试serialize表单或使用$.param作为POST参数

类似的,

 $.ajax({
            type:'POST',
            url:'submit_form.php',
            data:$('form').serialize()
            beforeSend: function () {
            },
            success:function(msg){
            }
        });

var postData = {
    "action": "test"
    "contactFrmSubmit": 1,
    "name": name,
    "email": email,
    "mobile": mobile,
    "location": location,
    "message": message
};
 $.ajax({
            type:'POST',
            url:'submit_form.php',
            data: postData,
            beforeSend: function () {
            },
            success:function(msg){
            }
        });

其次,在PHP文件中尝试查找传入的请求是否为ajax

if (is_ajax()) {
    if(isset($_POST['contactFrmSubmit']) 
       && !empty($_POST['name']) 
       && !empty($_POST['email']) 
       && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) 
       && !empty($_POST['mobile']) && !empty($_POST['location']) 
       && !empty($_POST['message']))
}

function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

最后,如果您打算返回更多值作为响应,请使用json_encode,这是一个通用标准

$response->status = "ok"
$response->status_code = 200
$json_response = json_encode($response);

return $json_response;
die();

虽然,以上只是为了您的理解,始终使用header()发送响应状态和代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多