0

我有一个表单,我想在它成功提交后隐藏它并显示一条消息(它已经在工作)。现在唯一的缺点是表单正在被滑动切换,即使它没有正确提交。提交表单时存在一些问题。它工作起来很奇怪。如果不是所有字段都填写,有时它会提交,有时它不会。我觉得php和jquery的配合在这里并不完美。

感谢帮助,我已经设法将这段代码放在一起:

PHP:

<?php
      $receip = "office@avehire.co.uk";
      $subj = "Testimonial";
      $bodymsg = "Name: ".$_POST['name']."\n"
                   ."Company: ".$_POST['company']."\n"
                   ."Email: ".$_POST['email']."\n"
                   ."Message: ".$_POST['msg']."\n";

          if(!$_POST['msg'] || $_POST['name'] || $_POST['email']){
                 echo "<h6>Error sending e-mail<h6>";
                 exit;
          }

      $email = $_POST['email'];
      if(mail($receip, $subj, $bodymsg, 'From: Contact <'.$email.'>')){
        echo "<h6>Message sent successfully. Thank you for your feedback.</h6>";
      }
?>

HTML + javascript 元素:

<div id="feedback-form">

    <script>                    
        function submitmyform(){
            data=$('#myform').serialize();
                $.ajax({
                url: "scripts/form-testimonial.php",
                type:'POST',
                data:data,
                async:false,
                dataType:'html',
                success: function(msg){

                    $('#response_goes_here').html(msg);
                    $("#feedback-form").slideToggle(200);
                }
            });

        }
    </script>

    <form action="" id="myform">

        <ul>
            <li>    <label for="name">Name</label>              <input id="namef3" name="name" type="text" placeholder="Name" class="required"/>            
          </li>
            <li>    <label for="email">E-mail</label>           <input id="emailf3" name="email" type="text" placeholder="E-mail" class="required"/>        
          </li>
            <li>    <label for="company">Company</label>        <input id="companyf3" name="company" type="text" placeholder="Company (if applicable)" />   
          </li>
            <li>    <label for="msg">Message</label>            <textarea id="msgf3" name="msg" cols="43" rows="8" placeholder="Your feedback" class="required"></textarea> 
          </li>
        </ul>
        <button type="button" class="submit" onClick="submitmyform();">Send your feedback</button>
    </form>
</div> <!-- id="feedback-form" -->
    <div id="response_goes_here"></div>

和一个验证脚本(对不起,它很长,我知道):

$(function () {
var addErrorMessage = function (field) {
    var err = $(document.createElement('p')).addClass('validation-error').text('Required field');
    field.addClass('err').after(err);
},
clearError = function () {
    var t = $(this);
    if (t.hasClass('err')) {
        t.removeClass('err');
        t.next('p').empty().remove();
    }
},
isEmpty = function (str) {
    return str.trim().length < 1;
},
isValidEmail = function (str) {
    var regexp = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regexp.test(str);
},
fieldsValidate = false;

function validateForm(e) {
    console.log('validate start');
    var requiredFields = jQuery(e).find('.required');
    var email = jQuery(e).find('input[name="email"]');
    var emailValue = email.val();
    console.log(emailValue+' mail val');
    fieldsValidate = true;
    // check that required fields are not empty
    requiredFields.each(function () {
        var t = $(this);
        if (isEmpty(t.val())) {
            fieldsValidate = false;
            if (!t.hasClass('err')) {
                addErrorMessage(t);
            }
        }
    });

    // check that email is valid
    console.log(isValidEmail(emailValue) + ' valid?');

    if (!isValidEmail(emailValue)) {
        fieldsValidate = false;
        if (!email.hasClass('err')) {
            addErrorMessage(email);
            console.log('mail NOT ok');
        }
    }
    console.log(fieldsValidate + ' before return');
    return fieldsValidate;
};

$('input, textarea').blur(clearError);

$(".submit").click(function() { return validateForm(this.form) });

我制作了一个jsFiddle,但它不包含实际的 php(我不知道我在 jsFiddle 中使用 php。

那么问题出在哪里:使用此页面上的表格:演示页面(请向下滚动并单击添加新证明 - 出现以下问题:

  1. 在未填写所有字段并单击提交后 - 它向上滑动表单(我希望它仅在正确填写表单时向上滑动)

  2. 当我删除 slideToggle 脚本时 - 即使它没有正确填写并且您再次单击 ADD NEW TSTIMONIAL... 以发送此表单并且不会填写它,然后它将发送实际消息(空),因此它会忽略验证表格。要测试此实例,请在 msg 字段中添加任何内容,并将其他内容留空。单击提交按钮几次后,它将忽略它们并发送表单。

可能是什么原因?问题出在哪里?奇怪的情况,难以用更简单的方式解释。感谢您对此的支持。

4

2 回答 2

1

代替

 echo "<h6>Message sent successfully. Thank you for your feedback.</h6>";

尝试

echo "sent";

然后在您的 jquery 脚本中:

success: function(msg){
               if(msg == 'sent'){
                        $('#response_goes_here').html('Message sent successfully. Thank you for your feedback.');
                        $("#feedback-form").slideToggle(200);
                    } else {
                     $('#response_goes_here').html('Error. Mail not sent!');
                   }

}

和这个

 if(!$_POST['msg'] || $_POST['name'] || $_POST['email']){
                 echo "<h6>Error sending e-mail<h6>";
                 exit;
          }

每次完成名称或电子邮件时都会返回错误:D。尝试

if(empty($_POST['msg']) || empty($_POST['name']) || empty($_POST['email'])){
   echo "<h6>Error sending e-mail<h6>";
                     exit;
}
于 2013-07-13T11:25:14.040 回答
1

有很多错误:

替换$(function () {(function ($) {

不要submitmyform点击按钮调用

代替

<button type="button" class="submit" onClick="submitmyform();">Send your feedback</button>

<button type="button" class="submit">Send your feedback</button>

不要在按钮单击时验证,而是调用表单提交并在提交处理程序中进行验证。如果表单有效,则调用submitmyform. 由于表单将使用 ajax 提交,提交处理程序将始终返回 false。为此,请替换以下代码:

$(".submit").click(function() { return validateForm(this.form) });

使用以下代码并尝试:

$(".submit").click(function() { 
    $("#myform").submit();
});

$("#myform").submit(function() {
    if (validateForm(this)) {
        console.log('valid');
        submitmyform();
    } else {
        console.log('invalid');
    }
    return false;
});

更新的 PHP 代码:

if (empty($_POST['msg']) || empty($_POST['name']) || empty($_POST['email'])) {
    echo "<h6>Error sending e-mail<h6>";
    exit();
}
$receip = "office@avehire.co.uk";
$subj = "Testimonial";
$bodymsg = "Name: " . $_POST['name'] . "\n"
        . "Company: " . $_POST['company'] . "\n"
        . "Email: " . $_POST['email'] . "\n"
        . "Message: " . $_POST['msg'] . "\n";

$email = $_POST['email'];
if (mail($receip, $subj, $bodymsg, 'From: Contact <' . $email . '>')) {
    echo "<h6>Message sent successfully. Thank you for your feedback.</h6>";
} else {
    echo "<h6>Error occurred while sending email.</h6>";
}
于 2013-07-13T12:30:00.037 回答