Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 提交后用成功消息替换HTML表单,表单使用单独的php文件发送邮件_Javascript_Php_Html_Forms - Fatal编程技术网

Javascript 提交后用成功消息替换HTML表单,表单使用单独的php文件发送邮件

Javascript 提交后用成功消息替换HTML表单,表单使用单独的php文件发送邮件,javascript,php,html,forms,Javascript,Php,Html,Forms,我有一个内置在index.html中的html联系人表单,然后我有一个mail.php文件,它发送邮件,还使用一些Javascript。当我填写表单并提交时,我已经将其编码为发送邮件,然后它会弹出一个成功消息框,然后重定向回index.html 我想要的是表单被替换为成功消息,以避免页面刷新,也避免弹出消息框 来自index.html的表单: <form action="mail.php" method="POST"> <div class="row uniform"

我有一个内置在index.html中的html联系人表单,然后我有一个mail.php文件,它发送邮件,还使用一些Javascript。当我填写表单并提交时,我已经将其编码为发送邮件,然后它会弹出一个成功消息框,然后重定向回index.html

我想要的是表单被替换为成功消息,以避免页面刷新,也避免弹出消息框

来自index.html的表单:

<form  action="mail.php" method="POST">
    <div class="row uniform">
    <div class="6u 12u$(xsmall)">
        <input type="text" name="name" id="name" value="" placeholder="Name" />
    </div>
    <div class="6u$ 12u$(xsmall)">
        <input type="email" name="email" id="email" value="" placeholder="Email" />
    </div>
    <div class="12u$">
        <!--<div class="select-wrapper">

        </div>-->
    </div>
    <div class="12u$">
        <textarea name="message" id="message" placeholder="Enter your message" rows="6"></textarea>
    </div>
        <center><div class="g-recaptcha" data-sitekey=""></div></center>
    <div class="12u$">
        <ul class="actions">
        <li><input type="submit" value="Send Message" class="special" /></li>
        <li><input type="reset" value="Reset" /></li>
        </ul>
    </div>
    </div>
</form>

php文件、电子邮件地址和recaptcha令牌已删除,原因很明显:

<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent = "From: $name \n email: $email \n Message: $message";
$recipient = 'email address here';
$subject = 'Message from Website';
$mailheader = "From: $email \r\n";
$captcha;
{
  if(isset($_POST['g-recaptcha-response']))
    {
      $captcha=$_POST['g-recaptcha-response'];
    }
  if(!$captcha)
    {
      echo '<script language="javascript">';
      echo 'alert("Please check the Captcha")';
      echo '</script>';
      exit;  
    }
  $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
  if($response.success==false)
  {
    echo '<h2>Please do not try and spam here.</h2>';
  }else
  {
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo '<script language="javascript">';
echo 'alert("Your Message successfully sent, we will get back to you ASAP.");';
echo 'window.location.href="index.html";';
echo '</script>';
  }
} ?>

您可以使用jQuery和Ajax表单提交来完成这项工作

首先,在head元素中包含jquery

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

接下来,给你的表格一个id

<form  id='mail_form' action="mail.php" method="POST">

在id='error'的某处添加一个span

<span id='error' style='color:red; font-weight:bold;'></span>

将mail.php调整为以下值:

<?php 
$success = true;
$errors = array();

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent = "From: $name \n email: $email \n Message: $message";
$recipient = 'email address here';
$subject = 'Message from Website';
$mailheader = "From: $email \r\n";
$captcha = false;

  if(isset($_POST['g-recaptcha-response']))
  {
      $captcha=$_POST['g-recaptcha-response'];
  }
  if(!$captcha)
  {
      $success = false;
      array_push($errors, "Please check the captcha");
  }
  $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
  if($response.success==false)
  {
    $success = false;
    array_push($errors, "Please do not try and spam here.");

  }

if ($success)
{
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
}

$output_array = array("success" => $success, "errors" => $errors);
echo json_encode($output_array);
 ?>

然后,在页面底部添加

<script>
$('#mail_form').on('submit', function(){
    var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to mail.php. Try doing alert(dataIn); to see what it holds.
    $.post( "./mail.php", dataIn )
        .done(function( dataOut )
        {
        //dataOut holds the response from mail.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
        var myArray = JSON.parse(dataOut );
        if (myArray['success'] == true) //Check if it was successfull.
            {
             $("#mail_form").html("Congrats! We just e-mailed you!");
            }
        else //there were errors
           { 
           $('#error').html(""); //Clear error span

            $.each(myArray['errors'], function(i){ 
            $('#error').append(myArray['errors'][i] + "<br>");
           }
        });
return false; //Make sure you do this or it will submit the form and redirect
});
</script>

$('mail#u form')。在('submit',function()上{
var dataIn=$(this).serialize();//serialize将表单数据转换为可以传递到mail.php的字符串。请尝试执行警报(dataIn);以查看它包含的内容。
$.post(“./mail.php”,数据输入)
.完成(功能(数据输出)
{
//dataOut保存来自mail.php的响应。响应将是任何html mail.php输出。我通常将json编码的数组作为响应进行回显,您可以在jQuery中解析这些响应。
var myArray=JSON.parse(dataOut);
if(myArray['success']==true)//检查它是否成功。
{
$(“#mail_form”).html(“恭喜!我们刚刚给你发了电子邮件!”);
}
否则就会出错
{ 
$('#error').html(“”;//清除错误范围
$.each(myArray['errors'],函数(i){
$('#error').append(myArray['errors'][i]+“
”); } }); return false;//确保执行此操作,否则它将提交表单并重定向 });
完成所有工作的最佳方法是使用ajax。在html中包含jquery

将表单放入包装器div中

<div class="something">
<!-- your form here -->
</div>
最后需要更改的是php代码

成功只有一个回声

echo "Your Message successfully sent, we will get back to you ASAP.";

首先,您应该使用AJAX调用提交表单。如果您坚持使用纯JS,脚本将如下所示(在5秒内编写-可能需要一些调整):


document.forms['yourForm'].onsubmit=function(form){//您必须向表单添加'name'属性,并用它替换'yourForm'
var data=…//这里您必须从表单元素中获取所有值并将它们存储在数据对象中。要减少对脚本的更改,请使用元素名称作为对象名称
if(window.XMLHttpRequest)
{
var xhReq=新的XMLHttpRequest();
}
其他的
{
var xhReq=新的ActiveXObject(“Microsoft.XMLHTTP”);
}
var方法='POST')
var async=false;//您实际上可以在这里设置为true,在这种情况下这并不重要
var url='mail.php';
open(方法、url、异步);
setRequestHeader(“内容类型”、“应用程序/x-www-form-urlencoded”);
setRequestHeader(“X-request-With”,“XMLHttpRequest”);
xhReq.send(数据);
document.getElementById(“表单的父级ID位于此处”).innerHTML=“新内容”
返回false;
}

然后,您必须从php文件中删除所有回声,因为它无论如何都不会显示。您还可以在此脚本中添加一些更复杂的内容,例如,检查邮件功能是否正常工作(通过在php文件中返回一些内容并在JS中检查AJAX响应)或者捕捉captcha错误。如果您愿意,在jQuery中也会非常容易实现。

仅供参考:
数据。消息将是未定义的,
数据本身将是一个字符串-
“您的消息成功发送,我们将尽快回复您。”
oops..我想我返回的是一个格式化的json…谢谢,我会更新我的答案。@SumitPandey我有兴趣尝试你的答案,我实现了hunijkah提交的答案,但是错误检查有一个错误,我一直在查看它,看看问题是什么,但是我对Ajax和jquery是新手。我的php文件已经有了所有的错误他检查了错误,所以我认为php文件仍然可以处理这个问题。你的答案能解决我的问题吗?我很快就要完成这项工作了,但错误检查实际上是唯一的障碍,如果表单填写正确,它会很好地工作。@Troy:嘿,如果你想使用hunijkah方法…只需一个更改..数组推送是一个函数ion不是一个变量。因此您必须将$array\u push更改为array\u push in mail。php@SumitPandey事实上,我现在尝试了你的方法,它工作得很好,正是我想要的方式。非常感谢!加上原生xhr req的1。所以我使用了你的解决方案,它确实有效。但是,我的错误检查不再有效,即,我只填写名称和一条没有填写电子邮件或勾选重述的消息,但它仍然带有一条成功消息,我应该做什么来确保我仍然得到与我使用php文件时相同的错误检查?@Troy更改为:
success
,并添加一个
。fail
您将能够根据服务器相应地输出响应。@Troy我刚刚更新了我的答案,以包括错误检查,就像我用JSON在评论中解释的那样arrays@hunijkah所以我做了你说的所有更改,当我填写所有字段并勾选验证码时,信息正确显示,然后我收到邮件。然后我尝试将电子邮件部分留空,勾选验证码,然后我t出现了致命错误:“函数名必须是第21行/mail.php中的一个字符串”,所以我猜不是
echo "Your Message successfully sent, we will get back to you ASAP.";
<script>

document.forms['yourForm'].onsubmit = function(form) { // you have to add 'name' attribute to the form and replace 'yourForm' with it
    var data = ... //here you have to get all the values from form elements and store them in data object. to make less changes to the script use the elements' names as object names
    if (window.XMLHttpRequest)
    {
        var xhReq = new XMLHttpRequest();
    }
    else
    {
        var xhReq = new ActiveXObject("Microsoft.XMLHTTP");
    }


    var method= 'POST')
    var async = false; //you can actually set true here, it doesn't matter much in this case
    var url = 'mail.php';
    xhReq.open(method, url, async);
    xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhReq.send(data);



    document.getElementById("form's parent's ID goes here").innerHTML = "new content"


    return false;
}
</script>