简体   繁体   English

使用JavaScript onClick在html按钮单击上发送PHP邮件,然后重定向到新的html页面

[英]Send PHP mail on html button click using JavaScript onClick then redirect to new html page

I am trying to send an email when an html button is clicked then redirect to an html confirmation page. 我试图在单击html按钮时发送电子邮件,然后重定向到html确认页面。 All my code is in the same php file except for the confirmation page. 除了确认页面,我所有的代码都在同一个php文件中。 It redirects with no problem just doesn't send email on button click. 它重定向没有问题,只是在单击按钮时不发送电子邮件。 It was working at one point but it would send the email as soon as the page loaded. 它在某一时间正常工作,但是它将在页面加载后立即发送电子邮件。 I've searched the internet for days and here is what I'm currently trying: 我已经在互联网上搜索了几天,这是我目前正在尝试的方法:

<form action="confirm.html" method="post" name= "confirm">
<?php

echo('<input type="button" value="Submit" onclick="this.form.submit();">');

?>
</form>

<?php

$to="mail@hello.com";
$subject= "New Application";
$message= "Name: ".$Name;
$headers= "";
mail($to, $subject, $message, $headers);

echo "<body onload=\"self.close();\">";


?>

I am trying to send an email when an html button is clicked then redirect to an html confirmation page. 我试图在单击html按钮时发送电子邮件,然后重定向到html确认页面。

The above code will send an email as soon as the page loads. 上面的代码将在页面加载后立即发送电子邮件。 If you want to send an email when the form has been submitted, you will need to wrap your emailing code in a post-checking block, the send a location header for the redirect. 如果要在提交表单后发送电子邮件,则需要将电子邮件代码包装在检查后块中,并发送重定向的location标头。

You also need some named element with a value to include in the post, for example: 您还需要一些带有值的命名元素以包含在帖子中,例如:

<input type="button" name="submit" value="Submit" />

Then in your PHP you can use 然后在您的PHP中,您可以使用

<?php
if (isset($_POST['submit'])) {
    // Your email() code

    // Redirect to another page
    header("Location: http://example.com/confirmation.php");
    die();
} else {
    // echo/include your form here

}

Be sure to put this code at the top of your PHP page before any HTML has been written or else header() will not function correctly. 在编写任何HTML之前,请确保将此代码放在PHP页面的顶部,否则header()将无法正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM