Form Button Refreshes on Click - One page Website

2019-08-22 08:37发布

问题:

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.

回答1:

@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!



回答2:

You can try using jquery ajax method

Create New File for send Email and in form attribute to give any id

<script>
$('#main-contact-form').submit(function(event){
event.preventDefault();
$.ajax({
    type:'post',
    url:'sendememail.php',
    data:$(this).serialize(),
    success:function(response){ 
        if(response==1)
        {   

            setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-success">Review Successfully Submited......</div></center></h5>');},5);

        }
        else 
        {

            setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-danger">Sorry Your Review Not Submit......</div></center></h5>');},5);

        }
    }

});
});
</script>


回答3:

For doing it in ajax, remove the form.action="" because it will reload the page.

Try

  • remove the action attribute from form.
  • remove the type=submit from button.
  • add the click event handler to button instead of adding it to form.submit.

The code will look like this

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form 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 id="submit" name="submit">Send Message</button>
</form>

jQuery

$(document).ready(function() {
  $('#submit').click(function(e) {
    e.preventDefault();
    $.post('index.php', $("form#contactForm").serialize(), function(data) {}).error(function(xhr) {alert(xhr)});
  });
});


回答4:

Use jQuery AJAX form submit and also Event.preventDefault(), so that page is not refreshed further.

for more help here is the link https://api.jquery.com/jquery.post/



回答5:

I think jQuery and AJAX is the way to go. I have a couple suggestions:

  1. Try moving the e.preventDefault() to before you do $.post. This should stop the event before it can reload the page and then send the email.

  2. Try using e.stopPropagation() in addition to or instead of e.preventDefault(). This will stop the event from bubbling up the DOM so that other elements won't trigger the reload.

  3. Try adding return false; to the end of the function. There was a similar question where this worked: Prevent form redirect OR refresh on submit?