PHP/JavaScript 电子邮件联系表单

3

我正在尝试使用联系表格发送电子邮件,提交后默认会重定向到另一个页面。但是,我想要提交电子邮件后仍停留在同一页上,并显示一个弹出消息告诉发件人邮件已发送,但不离开该页面。以下是我的HTML页面中的JavaScript和我尝试使用的PHP代码。

请问有谁能解释我错了什么,以及如何实现这一点吗?

<script type="text/javascript">
        $(document).ready(function() {

            $("#contactFormSubmit").click(function( event ) {
                $.post( “/contactengine.php", $("#contactForm").serialize() );
                $('#contactFormConfirmation').slideDown();
                $('#submitFormReset').click();
            });

        });
    </script>




<?php
$EmailFrom = "";
$EmailTo = "";
$Subject = "";
$Name = Trim(stripslashes($_POST['Name'])); 
$Email = Trim(stripslashes($_POST['Email'])); 
$Message = Trim(stripslashes($_POST['Message'])); 

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>

3
如果您想停留在同一页上,可以使用 Ajax。 - Slim
@slim你能给一个例子吗? - markkane
@markkane,请检查我的答案并告诉我是否遇到任何问题。 - Slim
3个回答

1

好的,我认为你应该尝试这个!

首先像发送邮件一样运行php脚本,然后在php脚本底部包含这一行

header("Location: http://myurl.com/contact?check=1");

然后在联系页面上添加一个名为check的隐藏输入,其值为0,然后使用url参数填充输入框。

在页面加载时检查隐藏输入框的值,以查看它是否为1或0。如果为1,则显示弹出框,如果为0,则正常加载页面。

希望这可以帮到你!

使用此代码

<form id="contactForm" method="post" action="contactengine.php">
    <div class="row half">
        <div class="6u">
            <input type="text" class="text" placeholder="Name" name="Name" />
        </div>
        <div class="6u">
            <input type="text" class="text" placeholder="Email" name="Email" />
        </div>
    </div>
    <div class="row half">
        <div class="12u">
            <textarea name="message" placeholder="Message" name="Message"></textarea>
        </div>
    </div>
    <div class="row" id="contactFormConfirmation" style="display: none;">
         <div class="12u">
             <p style="color: white; background-color: #FF3B30;width: 325px;border-radius: 0.25em;padding: .3em;margin: 0 auto;">Thank you for getting in touch!</p>
          </div>
    </div>
    <div class="row">
         <div class="12u">
             <ul class="actions">
                  <li>
                      <input type="submit" name="submit" id="contactFormSubmit" class="form-button" value="Submit" />
                  </li>
                  <li>
                      <input type="reset" name="reset" id="submitFormReset" class="form-button alt" value="Clear" />
                  </li>
             </ul>
         </div>
      </div>
  </form>
  <form name="checkf" id="checkf">
         <input name="check" id="check" value="0">
  </form>

编辑:

把你添加的代码更改为以下代码,我忘记在笑声中添加一行了。

<script type="text/css">
  function fcheckf(){
    var x = document.getElementById('check').value;
    if(x == 0)
    {
        return false;
    }
    else
    {
         alert("Thank you for submitting your data! - This is the pop up box content!");
    }
  }
</script>

一旦您添加了上述内容,请更改以下内容:

<body> 

将此

标签转换为:

<body onload="fcheckf()">

另一个编辑

现在在

之前添加以下内容:

</body>

标签。这很重要,它应该粘贴在body标签之前的行中 :)

<script type="text/javascript">
var data=location.search;
if(data) {
data=location.search.substring(1);
data=data.split('&');
var pairs={};
for(var i=0; i<data.length; i++){
    var tmp=data[i].split('=');
    pairs[tmp[0]]=tmp[1];
    }
var f = document.checkf;
for (var i in pairs) {
    if(f.elements[i]) {f.elements[i].value = pairs[i];}
    }
}

编辑 56981 V3

在您的 HTML 中使用此代码

<script>
function fcheckf(){
var x = document.getElementById('check').value;
if(x == 0)
{
    return false;
}
else
{
     alert("Thank you for submitting your data! - This is the pop up box content!");
}
 }
</script>
<section id="fourth" class="contact">
    <header>
        <div class="container">
            <span class="image-header-contact"><img src="images/contact-header.png" alt="Video" /></span>
            <h2>Get In Touch</h2>
        </div>
    </header>
    <div class="content style4 featured">
        <div class="container small">
            <form id="contactForm" method="post" action="contactengine.php">
 <div class="row half">
    <div class="6u">
        <input type="text" class="text" placeholder="Name" name="Name" />
    </div>
    <div class="6u">
        <input type="text" class="text" placeholder="Email" name="Email" />
    </div>
 </div>
 <div class="row half">
    <div class="12u">
        <textarea name="message" placeholder="Message" name="Message"></textarea>
    </div>
</div>
<div class="row" id="contactFormConfirmation" style="display: none;">
     <div class="12u">
         <p style="color: white; background-color: #FF3B30;width: 325px;border-radius: 0.25em;padding: .3em;margin: 0 auto;">Thank you for getting in touch!</p>
      </div> 
 </div>
 <div class="row">
     <div class="12u">
         <ul class="actions">
              <li>
                  <input type="submit" name="submit" id="contactFormSubmit" class="form-button" value="Submit" />
              </li>
              <li>
                  <input type="reset" name="reset" id="submitFormReset" class="form-button alt" value="Clear" />
              </li>
         </ul>
     </div>
  </div>
 </form>
 <form name="checkf" id="checkf">
     <input name="check" id="check" value="1">
 </form>
        </div>
    </div>
</section>
   <script>
       var data=location.search;
 if(data) {
 data=location.search.substring(1);
 data=data.split('&');
 var pairs={};
for(var i=0; i<data.length; i++){
var tmp=data[i].split('=');
pairs[tmp[0]]=tmp[1];
}
var f = document.checkf;
for (var i in pairs) {
if(f.elements[i]) {f.elements[i].value = pairs[i];}
}
}
    </script>

1
谢谢您的回复 - 您能展示一下这个是什么样子吗?因为我现在只能让它重新加载提交页面,但没有弹出窗口。 - markkane
好的,所以在您的页面上创建了一个ID为“check”,名称为“check”,值为0的隐藏输入框。 - KM123
我应该在<body>标签之前还是在HTML页面的</body>标签之前添加这个脚本? - markkane
刚刚在那里发布了我的朋友。 - KM123
显示剩余26条评论

1
如果你想停留在同一页,你应该使用ajax。我建议尝试使用jquery的$.ajax调用,因为它似乎更容易。
这里是一个简单的例子:
$.ajax({
    url: "pathToThePHPGoesHere", // Here you have to place the path to the php file
    type: 'GET',
    data: $.extend({
        mailSubject: encodeURI(mailSubjectVar), // 1st variable name and value - you can place the content of your HTML box here
        mailBody: encodeURI(mailBodyVar) // 2nd variable name and value - you can place the content of your HTML box here
    }, tJS.getCommonPostData()),
    dataType: "json",  
    cache: false,
    success: function (responseText, status, xhr) {
       alert("Job done!"); // Here is what happens when the request is executed
    },
    error: function (jqXHR, textStatus, error) {
        tJS.manageError(jqXHR); // show an error message if something goes wrong
    }
});

你需要在你的php脚本中进行变量解码。
我不是php开发人员,但你的代码应该如下所示:
$mailSubject = urldecode($_POST['mailSubject']);
$mailBody = urldecode($_POST['mailBody']);

.$ajax调用中,我已经对字符进行了编码,因此您可以传输UTF-8,这就是为什么您需要在php中使用urldecode的原因。
为了使用上述代码,请不要忘记在您的项目中包含jquery库。

0

做类似于这样的事情:

<script type="text/javascript">
    $(document).ready(function() {
        $("#contactFormSubmit").click(function( event ) {
            $.post("contactengine.php", $("#contactForm").serialize(), function(data) {
                $('#contactFormConfirmation').html(data.message).slideDown();
            },'json');
        });
    });
</script>

<?php

//code to send email here...
$success = true;

$result['status'] = "ok";
$result['message'] = "Your email has been sent.";
if (!$success){
    $result['status'] = "error";
    $result['message'] = "Unable to send your message.";
}
echo json_encode($result);
?>

它为什么不起作用?我在这里创建了一个JSFiddle:http://jsfiddle.net/scottfreeman/dC4Jb/,可能会有所帮助(请注意,如果您运行它,JSFiddle示例将无法正常工作,因为它不执行PHP操作)。 - scottfreeman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接