0

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.

Joe
  • 4,877
  • 5
  • 30
  • 51
  • 2
    What you seem to be looking for is called AJAX. – FirstOne Jun 08 '17 at 10:39
  • Ah! Thanks @FirstOne - just done a search on this after your suggestion and have a few options to test. Appreciate the comment. – Joe Jun 08 '17 at 10:46
  • @thickguru please check the answer and let me know if you have any problem – Sagar V Jun 21 '17 at 11:35
  • @thickguru Added a new answer. Good luck. –  Jun 21 '17 at 20:40
  • Possible duplicate of [Prevent form redirect OR refresh on submit?](https://stackoverflow.com/questions/1263852/prevent-form-redirect-or-refresh-on-submit) – Sagar V Jun 26 '17 at 15:22
  • 1
    SagarV I feel like the downvotes and the duplicate is because your answer wasn't accepted. Kinda funny xD.... I didn't get back to you with a video because @aendeerei had a better answer that worked. Not sure why you downvoted his answer also. Salty. – Joe Jun 26 '17 at 15:49
  • @SagarV Nope, my answer is no duplicate of that answer. That answer requires only to deactivate the form submit in order to execute a js/function. E.g. there takes place no php post-processing. Which is not the case in the question posted by thickguru. –  Jun 26 '17 at 17:02
  • 1
    I didn't downvoted. That is not a thing from my side. The dupe, I, sometimes visit old posts and I saw that one. Then I remembered of this post. I checked whether the open bounty is there. If it exists, the only option I have it to flag to mod. But since it is not there, I raised a dupe flag. – Sagar V Jun 26 '17 at 17:06
  • I didn't even knew you didn't accepted my answer and I didn't checked this for a while coz I didn't get a ping from you @thickguru – Sagar V Jun 26 '17 at 17:07
  • @aendeerei I didn't duped your answer. when I refer some old posts, I saw a question and then I remember of this. So, I CV'ed this to that. – Sagar V Jun 26 '17 at 17:10
  • @thickguru I appreciate the fact, that you're interested in finding why someone vote down an answer, question, etc. It's important that people know why their answers, questions, etc, are down-voted, because that way they know how or what to reedit, e.g. to make a better, clearer presentation. And, in the end, a better SO website, isn't it? I, personally, ask every time, "why the downvote". Do I receive an answer? Well... I just say "not always". –  Jun 26 '17 at 17:16
  • @SagarV I appreciate your explanation. Thanks. What does it mean "CV'ed"? –  Jun 26 '17 at 17:21
  • Close Voted. That is this question may be closed as a dupe of the other one. But nothing will happen to your rep. @aendeerei – Sagar V Jun 26 '17 at 17:22
  • @aendeerei while downvote other's post, try to leave a comment. – Sagar V Jun 26 '17 at 17:32
  • @SagarV What do you mean by "_while downvote other's post, try to leave a comment._"?! I did not downvoted no one's post. –  Jun 26 '17 at 17:36
  • I know. I say that while you downvoting someone's post in the future, you should leave a comment. That is a good practise – Sagar V Jun 26 '17 at 17:37
  • @SagarV Thank you for your advice. Even I don't see, why you would suddently give me such an advice :-) Actually I always motivate my downvotes and upvotes. –  Jun 27 '17 at 11:44

5 Answers5

1

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>
Joe
  • 4,877
  • 5
  • 30
  • 51
Harsh Panchal
  • 308
  • 1
  • 8
  • This didn't work I'm afraid. I set `$('#contactForm')` and changed the URL to `index.php` as this is a one page website. It simply done what the other solutions done, stopped it from refreshing the page but also stopped the contact form from working. Could it be the fact that it is a one page website causing this problem? – Joe Jun 08 '17 at 12:26
0

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/

Aurasphere
  • 3,841
  • 12
  • 44
  • 71
Sonali
  • 8
  • 2
0

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)});
  });
});
Sagar V
  • 12,158
  • 7
  • 41
  • 68
  • Thanks for the answer Sager. Annoyingly it didn't work. It still allowed me send the message, which is good. But the web page continued to refresh when I clicked the submit button. I copied the exact HTML that you suggested and added the jQuery within ` – Joe Jun 21 '17 at 12:16
  • @thickguru I made some small changes. Please try now. removed the `post` from `form`, add `event preventDefault`, likewise – Sagar V Jun 21 '17 at 12:32
  • Just applied the new changes. Same issue I'm afraid. But removing the `post` from `form` stopped the actual form from working and no longer sends the email. – Joe Jun 21 '17 at 12:37
  • @thickguru That is because of this `if(isset($_POST['submit'])){`. Change it to `if(isset($_POST['name'])){` – Sagar V Jun 21 '17 at 12:42
  • Made no difference. I think that is because the `post` was removed from the form. But the page is still refreshing too, so same issue :/... appreciate the help so far Sagar. – Joe Jun 21 '17 at 12:46
  • This issue looks weird. Can you make a screen record of this? – Sagar V Jun 21 '17 at 12:47
  • Of course, but I will have to do this once I'm home from work. Won't be able to do it right now. Thank you for your help Sagar. – Joe Jun 21 '17 at 13:17
  • 1
    Ping me along with YouTube link once you done. @thickguru – Sagar V Jun 21 '17 at 13:18
0

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?

sorayadragon
  • 1,087
  • 7
  • 21
0

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

  • Thanks for the answer. I've just tested it. What it is doing is when I submit the form, it actual directs to the `send_mail.php` page. The contact form works however, but now directs away from the homepage. – Joe Jun 21 '17 at 22:21
  • So when I fill in the form and select submit, instead of staying on `index.html` as it should, the page redirects to `send_mail.php` and away from the homepage. – Joe Jun 21 '17 at 22:26
  • @thickguru have you put `return false` in the function, as I did? Attention WHERE you put it! –  Jun 21 '17 at 22:31
  • OK, I've corrected that, I've put the code for `index.js` directly into the `index.html` code, which is now working. It sends the email correctly and I receive it without the page refreshing HURRAH! Final issue is that the alert now pops up saying that the email has failed. – Joe Jun 21 '17 at 22:34
  • @thickguru give me the exact alert message! –  Jun 21 '17 at 22:37
  • The alert message says `Email sending failed!` but it doesn't actually fail, it works lol... so not sure why it is popping up. – Joe Jun 21 '17 at 22:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/147317/discussion-between-aendeerei-and-thickguru). –  Jun 21 '17 at 22:38
  • 1
    Maybe the problem is in response type. I'll never use html, i'll prefer a JSON object and then write result in html object in the page or in alert. In addition if you yet have the problem of reloading page just use a – Andrea_86 Jun 22 '17 at 09:38
  • Thanks for your reply, @Andrea_86. We came to use the 'html' dataType because the initial tests with 'json' responded with an error and the 'html' version worked for thickguru. Actually, I prefer json too. The idea with the type 'button' is indeed a very good one. Based on your comment I decided to retest and extend the answer with all three possibilities. I'll reedit it in about an hour. Bye. –  Jun 22 '17 at 11:26
  • Yes, when using the dataType as `json` it threw an error. By using `html` it corrected that error. aendeerei originally suggested that I used `json`, but this did not work for my case. – Joe Jun 22 '17 at 12:12
  • 1
    @thickguru Thanks for your comment ;-) Actually, the json should work for you too. It's better to use it. And I have a feeling that, in your system the error can be resolved. I just think that you are printing or header-ing something before a json call, somewhere in your sytem. So, if you wish to resolve this once and for all, I stay to your disposal now. –  Jun 22 '17 at 12:27
  • 1
    @thickguru I extended my answer to present both options. NOTA BENE: Don't use custom names like "response", "name", "id", in your codes. Neither in js, html, php or mysql. It's error-prone. So, instead of div response, I used again "results". –  Jun 22 '17 at 12:30