简体   繁体   English

我使用PHP和JavaScript的第一个联系表单 - 无页面重定向

[英]My First Contact Form using PHP & JavaScript - No Page Redirect

Writing my first website that uses a contact form. 写我的第一个使用联系表格的网站。 In researching this myself so far, I came across the following article that I've been following: 到目前为止,我一直在研究这个问题,但我发现了以下我一直关注的文章:

http://www.nfriedly.com/techblog/2009/11/how-to-build-a-spam-free-contact-forms-without-captchas/ http://www.nfriedly.com/techblog/2009/11/how-to-build-a-spam-free-contact-forms-without-captchas/

So far, however, it's not working. 然而,到目前为止,它还没有奏效。 I have the contact page uploaded to a shared hosting server that has PHP on it. 我将联系页面上传到其上有PHP的共享主机服务器。 What follows is the code I have so far. 以下是我到目前为止的代码。

Here is the relevant content within the *.html file to the form: 以下是表单中* .html文件中的相关内容:

<form action="/submit.php" method="post">
    <span>Name</span>
    <br>
    <input id="name-text" type="text" name="name">
    <br>
    <span>Email</span>
    <br>
    <input id="email-text" type="text" name="email">
    <br>
    <span>Subject</span>
    <br>
    <input id="subject-text" type="text" name="subject">
    <br>
    <input id="antispam-text" type="text" name="url" style="display:none;">
    <span>Message</span>
    <br>
    <textarea id="message-text" name="message"></textarea>
    <br>
    <div class="form-submit">
        <input id="submit-button" class="menu" type="submit" value="Submit">
    </div>
    <br>
    <div class="form-submit">
        <span id="sent-status"></span>
    </div>
</form>

Here is the relevant content within the *.css file to the form: 以下是* .css文件中与表单相关的内容:

input[type="text"], textarea {
    width: 90%;
    margin: 10px;
    font-size: var(--font-text4);
}
textarea {
    height: 90px;
}
#submit-button:hover {
    border-color: #7AC943;
}
.form-submit {
    text-align: center;
    margin:-20px;
}
#submit-button {
    background-color: transparent;
    width: 150px;
    border: var(--thin-border);
    color: var(--font-color);
    font-size: var(--font-text3);
}
#sent-status {
    margin: -10px;
    padding: 7px;
    visibility: hidden;
    background-color: #000000;
}

Here is the relevant content within the *.js file to the form: 以下是* .js文件中与表单相关的内容:

document.getElementById('submit-button').addEventListener('click', function () {
    var formFilled = true;
    if (document.getElementById('name-text').value == '')
        formFilled = false;
    if (document.getElementById('email-text').value == '')
        formFilled = false;
    if (document.getElementById('subject-text').value == '')
        formFilled = false;
    if (document.getElementById('message-text').value == '')
        formFilled = false;
    document.getElementById('sent-status').style.visibility = 'visible';
    if (formFilled) {
        document.getElementById('sent-status').style.color = '#7AC943';
        document.getElementById('sent-status').innerText = 'Message Sent Successfully';
    }
    else {
        document.getElementById('sent-status').style.color = '#FF1D25';
        document.getElementById('sent-status').innerText = 'Contact Form Incomplete';
    }
});

Here is the entire contents of the submit.php file: 以下是submit.php文件的全部内容:

<?php
// If the URL field is empty...
if(isset($_POST['url']) && $_POST['url'] == ''){
    // then send the form to your email.
    mail('beta@email.com', 'Contact Form', print_r($_POST,true) );
}
// Else, let the spammer think that they got their message through.
?>

Here are the following technical issues that affect this contact form: 以下是影响此联系表单的以下技术问题:

  1. Filling out all fields of the form and clicking the Submit button, the browser then goes to the submit.php file and leaves the *.html file. 填写表单的所有字段并单击“提交”按钮,然后浏览器转到submit.php文件并保留* .html文件。 I want the browser to stay on the *.html file the whole time and never load the submit.php file as if it were a webpage. 我希望浏览器一直保留在* .html文件中,并且从不加载submit.php文件,就像它是一个网页一样。

  2. Clicking the Submit button, then checking the target email account I specified, nothing arrives in inbox nor spam. 单击“提交”按钮,然后检查我指定的目标电子邮件帐户,没有任何内容到达收件箱或垃圾邮件。 The email account otherwise sends/receives email messages just fine. 电子邮件帐户另外发送/接收电子邮件就好了。 In the submit.php code, you'll see I put beta@email.com which is not the actual target email. 在submit.php代码中,你会看到我把beta@email.com放在了不是真正的目标电子邮件中。 For this post, I'm keeping my actual email target address private. 对于这篇文章,我将实际的电子邮件目标地址保密。

Much appreciated for the assistance. 非常感谢您的帮助。

You can use the Fetch API, first prevent the default action of the submit button then send the form information using fetch like this: 您可以使用Fetch API,首先阻止提交按钮的默认操作,然后使用fetch发送表单信息,如下所示:

document.getElementById('submit-button').addEventListener('click', function (event) {
    event.preventDefault();

    var formFilled = true;
    if (document.getElementById('name-text').value == '')
        formFilled = false;
    if (document.getElementById('email-text').value == '')
        formFilled = false;
    if (document.getElementById('subject-text').value == '')
        formFilled = false;
    if (document.getElementById('message-text').value == '')
        formFilled = false;
    document.getElementById('sent-status').style.visibility = 'visible';
    if (formFilled) {
        const form = document.querySelector('form');
        const data = new FormData(form);

        fetch('/submit.php', {
            body: data,
            cache: 'no-cache',
            method: 'POST',
            mode: 'cors'
        })
        .then(res => res.text())
        .then(result => {
            if (result === 'ok') {
                document.getElementById('sent-status').style.color = '#7AC943';
                document.getElementById('sent-status').innerText = 'Message Sent Successfully';
            } else {
                //failed message here ...
            }
        });
    } else {
        document.getElementById('sent-status').style.color = '#FF1D25';
        document.getElementById('sent-status').innerText = 'Contact Form Incomplete';
    }
});

and make this change to the submit.php file: 并对submit.php文件进行此更改:

<?php
if(isset($_POST['url']) && $_POST['url'] == ''){
    extract($_POST);
    mail('beta@email.com', 'Contact Form', $message);

   echo 'ok';
}

in the mail function, the third argument should be the message, extract the message from the $_POST array and feed it to the mail function mail函数中,第三个参数应该是消息,从$ _POST数组中提取消息并将其提供给mail函数

You can try by using jQuery AJAX. 您可以尝试使用jQuery AJAX。 Here is a sample of code that can be helpful for you. 以下是可能对您有所帮助的代码示例。

HTML HTML

<form action="" method="post" id="myForm">
<span>Name</span>
<br>
<input id="name-text" type="text" name="name">
<br>
<span>Email</span>
<br>
<input id="email-text" type="text" name="email">
<br>
<span>Subject</span>
<br>
<input id="subject-text" type="text" name="subject">
<br>
<input id="antispam-text" type="text" name="url" style="display:none;">
<span>Message</span>
<br>
<textarea id="message-text" name="message"></textarea>
<br>
<div class="form-submit">
    <input id="submit-button" class="menu" type="submit" value="Submit">
</div>
<br>
<div class="form-submit">
    <span id="sent-status"></span>
</div>
</form>

Then in your js file put this code (I've skipped the validation process, but in your production code don't forget to do it!) 然后在你的js文件中放入这段代码(我已经跳过了验证过程,但在你的生产代码中不要忘记这样做!)

$(document).ready(function(){
    $('#myForm').on('submit',function(event){
    event.preventDefault();
    var data = $(this).serialize();
    $.ajax({
      type: 'POST',
      url: '/submit.php',
      data: data,
      success: function(response){
// do your code stuff here if all goes well
      },
      error: function(err){
// do your code stuff here in case of errors
      }
    });
  });
});

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

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