成功提交时隐藏表单

时间:2013-07-13 11:03:59

标签: php jquery forms validation slidetoggle

我有一个表单,我想在成功提交时隐藏它并显示一条消息(已经有效)。现在唯一的缺点是即使没有正确提交,表单也正在进行slideToggled。提交表单存在一些问题。它很奇怪。有时它会提交,如果不是所有字段都填满,有时它不会。我认为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。

所以问题出在哪里:使用此页面上的表单:demo page(请向下滚动并点击添加新的推荐 - 出现以下问题:

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

  2. 当我删除slideToggle脚本时 - 即使它未正确填充并且您再次点击添加新TSTIMONIAL ...再发送此表单并且不会填写它,那么它将发送实际消息(空),所以它忽略了验证表格。要测试此实例,请在msg字段上放置任何内容并将其他内容留空。它会忽略它们并在点击提交按钮后发送表单。

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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>";
}