提交返回主页

时间:2016-03-22 14:34:29

标签: php jquery html forms twitter-bootstrap

我在我的网站上使用一个简单的PHP联系表单,问题是当我发送邮件时,单击我的提交按钮会将我返回到主页。我想避免这种情况并留在页面上。

这是我的代码:

标题PHP:

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
    $hasError = true;
} else {
    $name = trim($_POST['contactname']);
}

//Check to make sure that the phone field is not empty
if(trim($_POST['phone']) == '') {
    $hasError = true;
} else {
    $phone = trim($_POST['phone']);
}

//Check to make sure that the name field is not empty
if(trim($_POST['weburl']) == '') {
    $hasError = true;
} else {
    $weburl = trim($_POST['weburl']);
}

//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
    $hasError = true;
} else {
    $subject = trim($_POST['subject']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '')  {
    $hasError = true;
} else if (!filter_var( trim($_POST['email'], FILTER_VALIDATE_EMAIL ))) {
    $hasError = true;
} else {
    $email = trim($_POST['email']);
}

//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
    $hasError = true;
} else {
    if(function_exists('stripslashes')) {
        $comments = stripslashes(trim($_POST['message']));
    } else {
        $comments = trim($_POST['message']);
    }
}

//If there is no error, send the email
if(!isset($hasError)) {
    $emailTo = 'myemail@email.com'; // Put your own email address here
    $body = "Name: $name \n\nEmail: $email \n\nPhone Number: $phone \n\nSubject: $subject \n\nComments:\n $comments";
    $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

    mail($emailTo, $subject, $body, $headers);
    $emailSent = true;
}
}
  ?>

形式:

  <div class="container">


<div class="row">
  <div class="col-md-6 col-md-push-3">
    <form role="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
      <fieldset>
        <legend>Send Us a Message</legend>

        <?php if(isset($hasError)) { //If errors are found ?>
          <p class="alert alert-danger">Please check if you've filled all the fields with valid information and try again. Thank you.</p>
        <?php } ?>

        <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
          <div class="alert alert-success">
            <p><strong>Message Successfully Sent!</strong></p>
            <p>Thank you for using our contact form, <strong><?php echo $name;?></strong>! Your email was successfully sent and we&rsquo;ll be in touch with you soon.</p>
          </div>
        <?php } ?>

        <div class="form-group">
          <label for="name">Your Name<span class="help-required">*</span></label>
          <input type="text" name="contactname" id="contactname" value="" class="form-control required" role="input" aria-required="true" />
        </div>

        <div class="form-group">
          <label for="phone">Your Phone Number<span class="help-required">*</span></label>
          <input type="text" name="phone" id="phone" value="" class="form-control required" role="input" aria-required="true" />
        </div>


        <div class="form-group">
          <label for="email">Your Email<span class="help-required">*</span></label>
          <input type="text" name="email" id="email" value="" class="form-control required email" role="input" aria-required="true" />
        </div>

        <div class="form-group">
          <label for="weburl">Your Website<span class="help-required">*</span></label>
          <input type="text" name="weburl" id="weburl" value="" class="form-control required url" role="input" aria-required="true" />
        </div>


        <div class="form-group">
          <label for="subject">Subject<span class="help-required">*</span></label>
          <select name="subject" id="subject" class="form-control required" role="select" aria-required="true">
            <option></option>
            <option>One</option>
            <option>Two</option>
          </select>
        </div>

        <div class="form-group">
          <label for="message">Message<span class="help-required">*</span></label>
          <textarea rows="8" name="message" id="message" class="form-control required" role="textbox" aria-required="true"></textarea>
        </div>

        <div class="actions">
          <input type="submit" value="Send Your Message" name="submit" id="submitButton" class="btn btn-primary" title="Click here to submit your message!" />
          <input type="reset" value="Clear Form" class="btn btn-danger" title="Remove all the data from the form." />
        </div>
      </fieldset>
    </form>
  </div><!-- col -->
</div><!-- row -->

  <hr>

  <div class="footer">
    <p>&copy; Company 2013</p>
  </div>

</div> <!-- /container -->

JS:

   /* Bootstrap Contact Form
      ***************************************************************************/
 $(document).ready(function(){
// validate signup form on keyup and submit


var validator = $("#contactform").validate({
    errorClass:'has-error',
    validClass:'has-success',
    errorElement:'div',
    highlight: function (element, errorClass, validClass) {
        $(element).closest('.form-control').addClass(errorClass).removeClass(validClass);
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).parents(".has-error").removeClass(errorClass).addClass(validClass);
    },
    rules: {
        contactname: {
            required: true,
            minlength: 2
        },
        email: {
            required: true,
            email: true
        },
        weburl: {
            required: true,
            url: true
        },
        phone: {
            required: true,
            phoneUS: true
        },
        subject: {
            required: true
        },
        message: {
            required: true,
            minlength: 10
        }
    },
    messages: {
        contactname: {
            required: '<span class="help-block">Please enter your name.</span>',
            minlength: jQuery.format('<span class="help-block">Your name needs to be at least {0} characters.</span>')
        },
        email: {
            required: '<span class="help-block">Please enter a valid email address.</span>',
            minlength: '<span class="help-block">Please enter a valid email address.</span>'
        },
        weburl: {
            required: '<span class="help-block">You need to enter the address to your website.</span>',
            url: jQuery.format('<span class="help-block">You need to enter a valid URL.</span>')
        },
        phone: {
            required: '<span class="help-block">You need to enter your phone number.</span>',
            phoneUS: jQuery.format('<span class="help-block">You need to enter a valid phone number.</span>')
        },
        subject: {
            required: '<span class="help-block">You need to enter a subject.</span>'
        },
        message: {
            required: '<span class="help-block">You need to enter a message.</span>',
            minlength: jQuery.format('<span class="help-block">Enter at least {0} characters.</span>')
        }
    }
   });
  });

我认为

可能存在问题
<form role="form" method="post" action="<?php echo   $_SERVER['PHP_SELF']; ?>" id="contactform">

使用

action="<?php echo $_SERVER['PHP_SELF']

我尝试删除它,并且还使用action =“#”但没有效果,提交按钮仍然会将我重定向到着陆页。

4 个答案:

答案 0 :(得分:1)

您提及&#34;整个网络只有一个主要网址,联系表单放置在没有网址的情况下的幻灯片面板中。我不确定你是如何生成幻灯片面板的,但我猜测它只是揭示/动画了该页面上已有的一些隐藏内容 - 可能是一个Bootstrap模式。

所以你有一个页面,也许是index.php,上面有一个联系表格。您的表单操作(数据发布到的位置)是<?php echo $_SERVER['PHP_SELF']; ?>,它将是&#34; index.php&#34; (检查,查看源代码或查看开发工具)。

所以点击提交,假设JS验证通过,将表单数据POST到index.php。 POST是一个新请求,因此在前端页面将显示为重新加载,但这次有一个POST负载,您的标头PHP将处理。您的联系表格将会消失,因为在点击链接或按钮或其他任何内容触发之前,它通常不会显示在页面上。

听起来您确实希望页面不刷新,并且联系表单显示将根据您的成功或错误信息更新(&#34;消息已成功发送!&#34;等)。要做到这一点,你需要通过AJAX进行POST,这将在后台进行而不刷新页面。

为此,您需要先更新PHP以返回您的Javascript可以使用的响应,而不是像在GET请求中那样生成整个页面。

if (isset($_POST['submit'])) {
    // ... all your existing code ...

    if ($hasError) {
        echo "FAIL";
    } else {
        echo "OK";
    }

    die();  // POSTs to this page only generate success/error msgs, and bail out
}

接下来,您需要为验证添加提交处理程序:

var validator = $("#contactform").validate({
    ...
    messages: {
    ...
    },
    submitHandler: function(form) {
        $.ajax({
            type: 'post',
            url: 'index.php',
            data: $(form).serialize(),
            success: function(data) {
                if (data === 'OK') {
                    // JS code to reveal your success alert, eg:
                    // $('div.alert-success').fadeIn();
                } else {
                    // JS code to reveal your danger alert
                }
            }
        });
        return false; // Block the normal submit, we just did it via AJAX
    }

最后,删除用于显示成功/危险警报的PHP条件,因为您现在将通过Javascript显示它们。只需添加一个&#34;隐藏&#34;对它们进行分类,以便在第一次加载时都不会显示。

通过只有一个警报区域,你可以通过PHP生成内容和类来使事情变得更加整洁,例如,而不仅仅是返回&#34; OK&#34;它可以返回JSON(确保在这种情况下将dataType:&#39; json&#39;添加到$ .ajax()调用中)。

答案 1 :(得分:0)

您必须在此属性中定义您的页面:

action="your_page.php"

答案 2 :(得分:0)

php echo $_SERVER['PHP_SELF']

它是root目录的路径,如/

表单在提交时有自己重新加载页面的能力,这就是为什么它会将你重定向到主页

在提交表单时,您应该使用AJAX留在此页面

答案 3 :(得分:0)

好的,由于您使用的是一个寻呼机而没有跟踪用户点击联系表单时的位置,因此您最简单的方法是使用target属性在隐藏的iframe中发送表单提交。然后使用javascript隐藏联系表单。

这样可以在发送表单时不重新加载页面。您也可以使用top在表单提交页面中编写JavaScript以向主页发送信息,并在表单正确提交时显示一条消息,例如“感谢您的反馈”。