简体   繁体   English

在不离开页面的情况下发送联系表格和 bootstrapValidator

[英]Send contact form without leaving the page and bootstrapValidator

I'm using this code from codepen for my contact form.我正在使用 codepen 中的此代码作为我的联系表格。

The issue that I'm experiencing is that once you click the "send" button, you leave the page where the contact form is to arrive to sendmessage.php.我遇到的问题是,一旦您单击“发送”按钮,您就会离开联系表单到达的页面到 sendmessage.php。

What I'd like to see is the normal behavior of a form: when you click "send" (and the message is transmitted successfully), you stay on the same page, the "send" button disappears and is replaced by the "success" message without leaving or reloading the page where the form is placed..我想看到的是表单的正常行为:当您单击“发送”(并且消息发送成功)时,您停留在同一页面上,“发送”按钮消失并被“成功”取代" 消息而无需离开或重新加载放置表单的页面..

Any idea what the issue is with the current code?知道当前代码有什么问题吗? You can test my live example here你可以在这里测试我的现场示例

Many thanks,非常感谢,

HTML: HTML:

<form class="well form-horizontal" action="../sendmessage.php" method="post"  id="contact_form">

Javascript: Javascript:

  $(document).ready(function() {
    $('#contact_form').bootstrapValidator({
        // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            first_name: {
                validators: {
                        stringLength: {
                        min: 2,
                    },
                        notEmpty: {
                        message: 'Please supply your first name'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'Please supply your email address'
                    },
                    emailAddress: {
                        message: 'Please supply a valid email address'
                    }
                }
            },            
            message: {
                validators: {
                      stringLength: {
                        min: 10,
                        max: 200,
                        message:'Please enter at least 10 characters and no more than 200'
                    },
                    notEmpty: {
                        message: 'Please supply a description of your project'
                    }
                    }
                }
            }
        })
        .on('success.form.bv', function(e) {
            $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...

                $('#contact_form').data('bootstrapValidator').resetForm();

            // Prevent form submission
            e.preventDefault();

            // Get the form instance
            var $form = $(e.target);

            // Get the BootstrapValidator instance
            var bv = $form.data('bootstrapValidator');

            // Use Ajax to submit form data
            $.post($form.attr('action'), $form.serialize(), function(result) {
                console.log(result);
            }, 'json');
        });
});

Content of sendmessage.php: sendmessage.php 的内容:

<?php

require 'PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

//Enable SMTP debugging. 
$mail->SMTPDebug = false;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.elasticemail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "xyz";                 
$mail->Password = "xyz";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 2525;                                   

$mail->From = $_POST['email'];
$mail->FromName = $_POST['first_name'];

$mail->addAddress("xyz@gmail.com");
//CC and BCC
$mail->addCC("xyz@outlook.com");
$mail->addBCC("");

$mail->isHTML(true);

$mail->Subject = "New message from " . $_POST['first_name'] . $_POST['last_name'];
$mail->Body =  $_POST['message']."<br><br>From page: ". str_replace("http://", "", $_SERVER['HTTP_REFERER']) . "<br>" . $_SERVER ['HTTP_USER_AGENT'] ;

$response = array();
if(!$mail->send()) {
  $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
  $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}

/* send content type header */
header('Content-Type: application/json');

/* send response as json */
echo json_encode($response);

?>

Have you tried doing just returning false on the submit event?您是否尝试过在提交事件中只返回 false?

$('#contact_form').on('submit', function(event) {
  event.preventDefault();
  return false;
});

You need to update your bootstrapvalidator.min.js file 0.4.5 to latest file您需要将 bootstrapvalidator.min.js 文件 0.4.5 更新为最新文件

https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js

I have created a fiddle https://jsfiddle.net/nwk9dLrn/8/ plz check but i have not added its ajax.php file but you can see it in console.我创建了一个小提琴https://jsfiddle.net/nwk9dLrn/8/请检查但我没有添加它的 ajax.php 文件,但你可以在控制台中看到它。 when you update your bootstrapvalidator file this will work.当您更新 bootstrapvalidator 文件时,这将起作用。

$('#contact_form').bootstrapValidator({
        // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            first_name: {
                validators: {
                        stringLength: {
                        min: 2,
                    },
                        notEmpty: {
                        message: 'Please supply your first name'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'Please supply your email address'
                    },
                    emailAddress: {
                        message: 'Please supply a valid email address'
                    }
                }
            },            
            message: {
                validators: {
                      stringLength: {
                        min: 10,
                        max: 200,
                        message:'Please enter at least 10 characters and no more than 200'
                    },
                    notEmpty: {
                        message: 'Please supply a description of your project'
                    }
                    }
                }
            }
        })
        .on('success.form.bv', function(e) {
            // Prevent form submission
            e.preventDefault();

            // Get the form instance
            var $form = $(e.target);

            // Get the BootstrapValidator instance
            var bv = $form.data('bootstrapValidator');

            // Use Ajax to submit form data
            $.post($form.attr('action'), $form.serialize(), function(result) {                
                $("#success_message").show();

                $('#contact_form input').val('');
            }, 'json');
        });

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

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