javascript 使用 PHP 和 AJAX 发送电子邮件表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30493055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:16:54  来源:igfitidea点击:

Sending e-mail form using PHP and AJAX

javascriptphpjqueryajaxforms

提问by Maryja Piaredryj

I have contact form on my site. It sends message to email. I try to do it without page reload using AJAX, but it seems that AJAX doesn't work: messages are sent but the page still redirecting to call-form.php. What is incorrect in my code? (jQuery is included)

我的网站上有联系表格。它将消息发送到电子邮件。我尝试在不使用 AJAX 重新加载页面的情况下执行此操作,但 AJAX 似乎不起作用:已发送消息但页面仍重定向到call-form.php. 我的代码有什么不正确?(包含 jQuery)

HTML

HTML

<form name="freeCall" action="<?php bloginfo(template_url); ?>/mail/call-form.php" method="post" class="popover-form" id="free-call-form">  
    <label for="name1">Name</label><span class="pull-right close">&times;</span><input placeholder="Name" name="call-name" type="text" id="name1" >  
    <label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >    
    <input type="submit" value="Call me back" >       
</form>

PHP - call-form.php

PHP - 调用-form.php

<?
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){ 
        $to = '[email protected]';
        $subject = 'Callback';
        $message = '
                <html>
                    <head>
                        <title>Call me back</title>
                    </head>
                    <body>
                        <p><b>Name:</b> '.$_POST['call-name'].'</p>
                        <p><b>Phonenum:</b> '.$_POST['phone'].'</p>                        
                    </body>
                </html>'; 
        $headers  = "Content-type: text/html; charset=utf-8 \r\n"; 
        $headers .= "From: Site <[email protected]>\r\n"; 
        mail($to, $subject, $message, $headers); 
}
?>

JS

JS

$(function () {    
      $("#free-call-form").submit(function () { 
        var form_data = $(this).serialize(); 
        $.ajax({
          type: "POST", 
          url: "call-form.php", 
          data: form_data,
          success: function () {
            alert("It's OK!");
          }
        });
      }); 
});

回答by w3spi

Ok, first when you make an AJAX call, you must have a way to know if your PHP returns you something (useful for debugging).

好的,首先当你进行 AJAX 调用时,你必须有办法知道你的 PHP 是否返回了一些东西(对调试很有用)。

Then, when submitting a form with AJAX, the tag action=""is not needed.

然后,当使用 AJAX 提交表单时,action=""不需要标记。

Finally, to prevent a form from being sent when making an AJAX call, add e.preventDefault()with the event called ehere, like in my example.

最后,为了防止在进行 AJAX 调用时发送表单,请添加此处调用e.preventDefault()的事件e,就像我的示例一样。

I have improved your code to be more realistic about the latest standards.

我已经改进了您的代码,使其更符合最新标准。

HTML :

HTML :

<form name="freeCall" method="post" class="popover-form" id="free-call-form">  
  <label for="name1">Name</label><span class="pull-right close">&times;</span><input placeholder="Name" name="call-name" type="text" id="name1" >  
  <label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >    
  <input type="submit" value="Call me back" >       

JS :

JS:

$(function () {    
  $("#free-call-form").submit(function (e) {
    e.preventDefault();
    var form_data = $(this).serialize(); 
    $.ajax({
      type: "POST", 
      url: "call-form.php",
      dataType: "json", // Add datatype
      data: form_data
    }).done(function (data) {
        console.log(data);
        alert("It's OK!");
    }).fail(function (data) {
        console.log(data);
    });
  }); 
});

And PHP :

和 PHP :

if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){ 
  $to = '[email protected]';
  $subject = 'Callback';
  $message = '
        <html>
            <head>
                <title>Call me back</title>
            </head>
            <body>
                <p><b>Name:</b> '.$_POST['call-name'].'</p>
                <p><b>Phonenum:</b> '.$_POST['phone'].'</p>                        
            </body>
        </html>'; 
  $headers  = "Content-type: text/html; charset=utf-8 \r\n"; 
$headers .= "From: Site <[email protected]>\r\n"; 
mail($to, $subject, $message, $headers);

  echo json_encode(array('status' => 'success'));
} else {
  echo json_encode(array('status' => 'error'));
}

With echo json_encode, you know what is the return of your AJAX call. It is better

使用echo json_encode,您就知道 AJAX 调用的返回值是什么。这个比较好

回答by Jay Blanchard

You're not preventing the default submit action -

您没有阻止默认提交操作 -

$("#free-call-form").submit(function (event) { // capture the event
    event.preventDefault();  // prevent the event's default action

回答by ecarrizo

Returning false or preventing the default behavior of the event should work for you.

返回 false 或阻止事件的默认行为应该对您有用。

Example with old .submit(), that now is an alias of .on('eventName'); and using return false to avoid form submission.;

旧的 .submit() 示例,现在是 .on('eventName'); 的别名;并使用 return false 避免提交表单。

 $("#free-call-form").submit(function () { 
    var form_data = $(this).serialize(); 
    $.ajax({
        type: "POST", 
        url: "call-form.php", 
        data: form_data,
        success: function () {
          alert("It's OK!");
      }
    });
    return false;
}); 

Example using .on('eventName') and using e.preventDefault() to avoid form submission.

使用 .on('eventName') 和使用 e.preventDefault() 来避免表单提交的示例。

$("#free-call-form").on('submit', function (e) { 
    e.preventDefault();
    var form_data = $(this).serialize(); 
    $.ajax({
        type: "POST", 
        url: "call-form.php", 
        data: form_data,
        success: function () {
          alert("It's OK!");
      }
    });
}); 

From Jquery .submit() Documentation: This method is a shortcut for .on( "submit", handler ) in the first variation, > and .trigger( "submit" ) in the third.

来自 Jquery .submit() 文档:此方法是第一个变体中的 .on( "submit", handler )、第三个变体中的 > 和 .trigger( "submit" ) 的快捷方式。

Also, you would consider not using EVER the user input directly, it would not cause problems in this exact context (or maybe yes) but with your actual approach they can change the mail markup or adding some weirds things there, even scripts, you would consider escape, validate or limit it.

此外,您会考虑不直接使用用户输入,它不会在这种确切的上下文中引起问题(或者可能是)但是通过您的实际方法,他们可以更改邮件标记或在那里添加一些奇怪的东西,甚至是脚本,您会考虑逃避、验证或限制它。

Also as zLen pointed out in the comments:

同样正如 zLen 在评论中指出的那样:

the action in the form markup is not necessary because you are not using it, you can remove it:

表单标记中的操作不是必需的,因为您没有使用它,您可以将其删除:

action="<?php bloginfo(template_url); ?>/mail/call-form.php"

回答by squill25

What is happening is your form is being submitted, it's not actually the AJAX call which is doing it. To fix it, add

发生的事情是您的表单正在提交,实际上并不是 AJAX 调用在执行此操作。要修复它,请添加

return false;

at the end of the submitfunction so that the browser doesn't submit the form and the AJAX call happens properly.

submit函数的末尾,这样浏览器就不会提交表单并且 AJAX 调用正确发生。