表单按钮刷新 - 单页网站 [英] Form Button Refreshes on Click - One page Website

查看:121
本文介绍了表单按钮刷新 - 单页网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个联系表单,以便用户可以向我们发送电子邮件。但是,每次点击发送电子邮件时,它也会在点击时刷新页面。这是一个单页的网站。



我尝试了以下建议的修复:

使用<按钮> 元素或使用< input type =button/> 。以及以下建议的修复:防止页面内的按钮被刷新时刷新页面



通过添加 onclick =return false;



这两个修复程序都会在按钮被点击时停止刷新页面,但是它也会阻止联系表单实际工作,不再发送电子邮件给我们。



我也更新了我的PHP,以反映该类型的名称更改。



我的PHP是:

 <?php 
if(isset($ _ POST ['submit'])){
$ to =example@example.com; //这是你的电子邮件地址
$ = = $ _POST ['email']; //这是发件人的电子邮件地址
$ name = $ _POST ['name'];
$ subject =表单提交;
$ subject2 =表单提交副本;
$ message = $ name。 写道:。 \\\
\\\
。 $ _POST [消息];
$ message2 =这是你的信息的副本。 $名称。 \\\
\\\
。 $ _POST [消息];

$ headers =From:。从$;
$ headers2 =From:。 $到;
邮件($ to,$ subject,$ message,$ headers);
邮件($ from,$ subject2,$ message2,$ headers2); //将消息副本发送给发件人
echoMail Sent。Thank you。 $名称。 , 我们会尽快与您联系。;

}
?>

我的HTML是:

 < form action =method =postid =contactForm> 
< input type =textname =nameid =nameplaceholder =Name ...>
< input type =textname =emailid =emailplaceholder =Email ...>
< p>< br>< / p>
< textarea name =messageid =messagecols =40rows =3spellcheck =trueplaceholder =Message ...>< / textarea>
< p>< br>< / p>
< button type =submitid =submitname =submitonclick =return false;>发送消息< / button>
< / form>

目前用于发送电子邮件,但不会阻止其刷新页面。希望有任何帮助,为什么这样做..



编辑:



<我已经尝试了一些使用AJAX的不同选项,因为它被认为是最好的选择。所有成功地停止页面刷新,但所有的选项再次,停止我的联系表格工作。我试过:

1:

 (函数(){
$('#contactForm')。on('submit',function(e){
$ .post('index.php',$(this).serialize (),function(data){
//当mail.php的调用成功时执行
//'data'包含请求
})的响应。 (function(){
//当mail.php的调用失败时执行
});
e.preventDefault();
});
});

2:

  $(#contactForm)。submit(function(e){
e.preventDefault();
});

3:

我也尝试过为严苛的潘卡尔提供给我的答案。


解决方案

@thickguru,不期望接收工作解决方案 - 带或不带ajax - 如果您使用< form> ...< / form> 保持邮件在同一页面上发送php代码。即使页面没有刷新,那么即使使用ajax,页面也必须从ajax结果重新生成(这是一个不良选项)。所以,你必须在不同的页面中分离这两个任务,并且只有在使用ajax之后。这样你实现(见的关注分离的一个漂亮的关注点分离 - 至少第一段)

以下是使用ajax提交表单的两个选项。

1。使用'json'数据类型(推荐)提交表单:



页面send_mail.php:



NOTA BENE:不再有 if(isset($ _ POST ['submit'])){...} 。如果使用此验证,它将失败,因为默认情况下,提交按钮不会作为POST变量的一部分发送。如果您想要仍然验证$ _POST数组,您必须手动将其指定为发送的 data 对象中的属性。



注意使用json编码函数 json_encode

 <?php 
$ to =example@example.com; //这是你的电子邮件地址
// ...
$ message =邮件发送。谢谢。 $名称。 , 我们会尽快与您联系。;
echo json_encode($ message);
?>



页面index.html:



> onclick
$ b

 < div id =results>< / div> 
< form id =contactFormname =contactFormaction =send_mail.phpmethod =post>
<! - - ...表单输入... - >
< button type =submitid =submitname =submit>提交< / button>
< / form>



页面index.js(例如您的文件带有js脚本):



  / ** 
*在文档准备就绪。
*
* @return void
* /
$(document).ready(function(){
sendEmail();
});

/ **
*发送电子邮件。
*
* @return void
* /
函数sendEmail(){
var contactForm = $('#contactForm');
var results = $('#results');

contactForm.submit(function(event){
var ajax = $ .ajax({
method:'post',
dataType:'json',
url:'send_mail.php',
data:contactForm.serialize()
});
ajax.done(function(response,textStatus,jqXHR){
results.html(响应);
});
ajax.fail(函数(jqXHR,textStatus,errorThrown){
results.html( '电子邮件发送失败!');
)};
ajax.always(function(response,textStatus,jqXHR){
// ...
});

return false;
});

NOTA BENE :如果您决定使用表单提交验证,你必须处理所有情况。例如,当你像这样使用它时,你会收到一个错误:

  if(isset($ _ POST ['submit' ])){
// ...
$ message =邮件发送。谢谢。 $名称。 , 我们会尽快与您联系。;
echo json_encode('Hello,World!');

$ / code>

解决方案是将未设置的POST'submit'作为well:

  if(isset($ _ POST ['submit'])){
// ...
$ message =发送邮件,谢谢。 $名称。 , 我们会尽快与您联系。;
echo json_encode('Hello,World!');
} else {
echo json_encode('Submit button not recognized');
}






2。使用'html'数据类型提交表单:



Pagesend_mail.php:



NOTA BENE: dito。

 <?php 
$ to =example@example.com ; //这是你的电子邮件地址
// ...
$ message =邮件发送。谢谢。 $名称。 , 我们会尽快与您联系。;
echo $ message;
?>



页面index.html:



DIV>
< form id =contactFormname =contactFormaction =send_mail.phpmethod =post>
<! - - ...表单输入... - >
< button type =submitid =submitname =submit>提交< / button>
< / form>



页面index.js:



  / ** 
*在文档准备就绪。
*
* @return void
* /
$(document).ready(function(){
sendEmail();
});

/ **
*发送电子邮件。
*
* @return void
* /
函数sendEmail(){
var contactForm = $('#contactForm');
var results = $('#results');

contactForm.submit(function(event){
var ajax = $ .ajax({
method:'post',
dataType:'html',
url:'send_mail.php',
data:contactForm.serialize()
});
ajax.done(function(response,textStatus,jqXHR){
results.html(响应),
});
ajax.fail(函数(jqXHR,textStatus,errorThrown){
results.html( '电子邮件发送故障!');
)};
ajax.always(function(response,textStatus,jqXHR){
// ...
});

return false;
});
}

我建议你不要使用<$ c的短手ajax版本$ c> post 或 get 。你有更多的灵活性与正常的ajax调用。

I've created a contact form so that users can send us an email. However, every time I click to send the email it also refreshes the page when clicked. This is a one page website.

I've attempted the fixes suggested in: How do I make an HTML button not reload the page

by using either the <button> element or use an <input type="button"/>. and also the fixes suggested in: prevent refresh of page when button inside form clicked

by adding onclick="return false;".

Both of these fixes stop the button from refreshing the page when it is clicked, however, it also stops the contact form from actually working and no longer sends an email to us.

I also updated my PHP to reflect the name changes of the type.

My PHP is:

<?php
   if(isset($_POST['submit'])){
   $to = "example@example.com"; // this is your Email address
   $from = $_POST['email']; // this is the sender's Email address
   $name = $_POST['name'];
   $subject = "Form submission";
   $subject2 = "Copy of your form submission";
   $message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
   $message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];

   $headers = "From:" . $from;
   $headers2 = "From:" . $to;
   mail($to,$subject,$message,$headers);
   mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
   echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";

   }
?>

My HTML is:

<form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>

This currently works for sending the email, but does not stop it from refreshing the page. Would appreciate any help as to why it is doing this..

EDIT:

I've tried a few different options using AJAX since it was suggested this was the best route to take. All successfully stopped the page from refreshing, but all the options once again, stopped my contact form from working. I tried:

1:

$(function() {
    $('#contactForm').on('submit', function(e) {
        $.post('index.php', $(this).serialize(), function (data) {
            // This is executed when the call to mail.php was succesful.
            // 'data' contains the response from the request
        }).error(function() {
            // This is executed when the call to mail.php failed.
        });
        e.preventDefault();
    });
});

2:

$("#contactForm").submit(function(e) {
    e.preventDefault();
});

3:

I also tried the answer offered to me by Harsh Panchal.

解决方案

@thickguru, don't expect to receive a working solution - with or without ajax - if you maintain your mail sending php code on the SAME page with the <form>...</form>. Even if the page does not refresh, then even if you are using ajax, the page must be rebuilded from the ajax results (which is a BAD option). So, you must separate the two tasks in DIFFERENT pages and only after that use ajax. In this way you achieve a beautiful "separation of concerns" (see Separation of concerns - at least the first paragraph).

Here are two options of submitting the form by using ajax.

1. Submit the form using 'json' data type (recommended):

Page "send_mail.php":

NOTA BENE: No more if(isset($_POST['submit'])){...}. If you use this validation it will fail, because, by default, the submit button will NOT be sent as part of the POST variables. You would have to manually assign it as property in the sent data object if you'd want to still validate the $_POST array.

Notice the use of the json encoding function json_encode.

<?php
    $to = "example@example.com"; // this is your Email address
    //...
    $message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
    echo json_encode($message);
?>

Page "index.html":

NOTA BENE: No onclick attribute on submit button!

<div id="results"></div>
<form id="contactForm" name="contactForm" action="send_mail.php" method="post">
    <!-- ... The form inputs ... -->
    <button type="submit" id="submit" name="submit">Submit</button>
</form>

Page "index.js" (e.g your file with the js scripts):

/**
 * On document ready.
 * 
 * @return void
 */
$(document).ready(function () {
    sendEmail();
});

/**
 * Send email.
 * 
 * @return void
 */
function sendEmail() {
    var contactForm = $('#contactForm');
    var results = $('#results');

    contactForm.submit(function (event) {
        var ajax = $.ajax({
            method: 'post',
            dataType: 'json',
            url: 'send_mail.php',
            data: contactForm.serialize()
        });
        ajax.done(function (response, textStatus, jqXHR) {
            results.html(response);
        });
        ajax.fail(function (jqXHR, textStatus, errorThrown) {
            results.html('Email sending failed!');
        });
        ajax.always(function (response, textStatus, jqXHR) {
            // ...
        });

        return false;
    });
}

NOTA BENE: If you decide to use form submit validation, you have to handle ALL situations. For example, when you use it like this, you will receive an error:

if (isset($_POST['submit'])) {
    //...
    $message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
    echo json_encode('Hello, World!');
}

The solution is to handle the not-is-set POST 'submit' as well:

if (isset($_POST['submit'])) {
    //...
    $message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
    echo json_encode('Hello, World!');
} else {
    echo json_encode('Submit button not recognized');
}


2. Submit the form using 'html' data type:

Page "send_mail.php":

NOTA BENE: dito.

<?php
$to = "example@example.com"; // this is your Email address
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo $message;
?>

Page "index.html":

NOTA BENE: dito.

<div id="results"></div>
<form id="contactForm" name="contactForm" action="send_mail.php" method="post">
    <!-- ... The form inputs ... -->
    <button type="submit" id="submit" name="submit">Submit</button>
</form>

Page "index.js":

/**
 * On document ready.
 * 
 * @return void
 */
$(document).ready(function () {
    sendEmail();
});

/**
 * Send email.
 * 
 * @return void
 */
function sendEmail() {
    var contactForm = $('#contactForm');
    var results = $('#results');

    contactForm.submit(function (event) {
        var ajax = $.ajax({
            method: 'post',
            dataType: 'html',
            url: 'send_mail.php',
            data: contactForm.serialize()
        });
        ajax.done(function (response, textStatus, jqXHR) {
            results.html(response);
        });
        ajax.fail(function (jqXHR, textStatus, errorThrown) {
            results.html('Email sending failed!');
        });
        ajax.always(function (response, textStatus, jqXHR) {
            // ...
        });

        return false;
    });
}

I suggest you to not use the short-hand ajax version of post or get. You have more flexibility with a normal ajax call.

Good luck!

这篇关于表单按钮刷新 - 单页网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆