views:

158

answers:

3

I am in the process of creating a PHP contact form and all I have is that little problem, with the php script I have, that when the email was send out a new "Thank you" page is called.So the actual site with the contact form disappears BUT I DON`T WANT THAT HAPPEN.

If the send button is hit I want to stay on my site, showing an empty contact form and maybe below the contact form just 1 line, saying "Thank you.....".

How can I make that happen? Is there any code snippet out there that can explain to me what I have to include to my html and to my php file? Hopefully it will...Below is how my php ends right now.

// send Email 
if (@mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader ))
{
    // if email was successfully send
    echo 'Thank you for your Email. We will get in touch with you very soon.';
}

EDIT
@FreekOne
Currently I am using your code with a slight modification because I wanted to make the thank you and or error panel make slide out and have the text fade in. The script is accepting my code (because it is still working) but actually I can not see that the text actually fades in. I have seen samples of sliding panels with fading in text. So it seems to be a wrong kind of coding that I did.
Please view the code here if you want:
http://jsbin.com/ohuya3
A working example of the form is available here:
http://cozyphant-living.com/php/formular4.htm
Maybe you can point me to the right direction. Of course, help would be appreciated from all of you guys here around.

+4  A: 

Set the form to send the data to the same page, and have your script listen for a submit. Something like:

contact.php

<?php
// Check if form was previously submitted
if(isset($_POST['myFormSubmitted'])) {
    // Do your form processing here and set the response
    $response = 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
<!-- HTML here -->
<?php
if (isset($response)) { // If a response was set, print it out
    echo $response;
}
?>
<form method="POST" action="contact.php">
    <!-- Your inputs go here -->
    <input type="submit" name="myFormSubmitted" value="Submit">
</form>
<!-- More HTML here -->

UPDATE

Considering the provided extra info, I would personally do it with jQuery, through AJAX. First, setup your form and the container for the result:

HTML

<form id="myForm" method="POST" action="contact.php">
    <input type="text" id="name" name="name">
    <input type="text" id="email" name="email">
    <input type="text" id="message" name="message">
    <input type="submit" name="myFormSubmitted" value="Submit">
</form>
<div id="formResponse" style="display: none;"></div>

Then setup the php script which handles the submitted data and outputs the response.

PHP (contact.php)

<?php
if(isset($_POST['myFormSubmitted'])) {
    // Do your form processing here and set the response
    echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>

And finally, the jQuery script which will submit your form without leaving the page and insert the result in your result container (with a nice and simple fade in effect).

jQuery

$("#myForm").submit(function() {
    $.post('contact.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'}, function(data) {
        $("#formResponse").html(data).fadeIn('100');
        $('#name, #email, #message').val(''); /* Clear the inputs */
    }, 'text');
    return false;
});

Hope this helps !

FreekOne
@FreekOne I think your solution comes very close to what I want but I need some time to figure out how to use it. It is a complete different approach. Right now I am using a mailbody with text placeholder like this<br> $mailbody = file_get_contents( 'mailbody.txt' ); $mailbody = str_replace( '###NAME###', htmlspecialchars( $name ), $mailbody ); $mailbody = str_replace( '###EMAIL###', $email, $mailbody ); $mailbody = str_replace( '###NACHRICHT###', htmlspecialchars( $nachricht ), $mailbody );<br><br>I would not need this anymore - RIGHT? But what happens if javascript is disabled?
Hardy
why can´t I use any codes in that comment section, sorry about this........hope you understand anyway.....
Hardy
No, you would still need that, and you would also have to define `$name`, `$email`, `$nachricht`. If JS is disabled, the form would still be correctly submitted although the user would see only a white page with the "thank you" message on it.
FreekOne
I am also curious on how to gracefully degrade to a php script that exists outside of the file you are submitting from (file a) while still maintaining file a's html structure...
Dave Kiss
@Hardy, you need to use ` around the code in comments just like in questions/answers, although I'd strongly suggest you edit your original question any place any additional code there, properly formatted because it is a lot easier to read.
FreekOne
@Dave Kiss - Not sure how to do it with separate php script, but the closest to degrading gracefully I guess would be to combine both my solutions. Submit the form through AJAX to the same page. If JS is enabled, it will work as expected, otherwise the user will see a reload.
FreekOne
@FreekOne - Wow, you are my Hero of today. After some swet and finding out that I have to build your solution "around" my exsisting php script - IT WORKED!!!!!!!!!!! The visitor stays on the page with the form and the thank you message fades in and most of all, the mail actually arrives. Only 1 downside.....the filled in text does not disappear. I would have loved to see that as well but it is ok. I can good live with your solution. THANK YOU AGAIN.
Hardy
Glad to be of help :) Please take another look at the jQuery part in my answer. I have updated it with a line that should also clear your input fields when the form is being submitted.
FreekOne
@FreekOne - 2nd line did the trick. you are the best. thank you really, really much. You made my day.
Hardy
@FreekOne - Maybe you can answer me that 1 more question. You said this is jQuery, through AJAX. I play a lot with jQ already but I am not exactly sure about that AJAX. I mean I know what it is doing but what is the part of the code we use in that example that makes the whole thing AJAX? Any easy to follow explanation?
Hardy
The [AJAX](http://api.jquery.com/jQuery.ajax/) part of the code is [`.post()`](http://api.jquery.com/jQuery.post/) which is shorthand for `.ajax({type: 'post', ...` - both of those two links should provide you with plenty of explanations and examples.
FreekOne
@FreekOne - Good Morning. If you have a second, could you have a look at my latest Edit. Would need some direction. Thanks.
Hardy
@FreekOne - forgot to mention. If you view the working example, you have to hit the blue "Formular senden" button to see what I am talking about.
Hardy
@Hardy: since this is a different issue than the one on your original question, please post a new question with an appropriate title. If you keep developing this question, anyone reading this in search of a solution to a problem similar to your original question would get very confused.
FreekOne
OK, will do but it is a little confusing for me to use this portal. It seems to be very, very restrictive. Sorry for doing something wrong. I am using it only for 5 days or so but I will learn fast - hopefully.
Hardy
It's not really restrictive at all. It just falls onto all of us to try and keep this as organized as possible so the information is easy to find. Having a problem, and fining that the actual answer is buried under a bunch of follow up questions would be much more confusing. Imagine SO as more of a Question/Answers Wiki than a forum, if you wish.
FreekOne
A: 

you could use same page to input and process the form's query. something like this might be work:

if(isset($_POST['submit'])) {
  //form validation and processing
  echo '<b>thank you</b>';
} else {?>
  <form action="thisfile.php" method="POST">
  </form>
}

ofc this is the simplest way to do that. More complicated way is to use AJAX to process the form.

bangbambang
sorry for late and nearly-duplicate comment. My connection just a bit too old :(
bangbambang
You're missing a bracket there. Also this would only output the "thank you" message without the form, which is not what the OP asked.
FreekOne
yep, my fault :D
bangbambang
I didn't even notice the missing single quote and the missing semicolon. But the bracket is still missing -- `else` isn't closed.
FreekOne
@FreekOne @bangbambang<br>Thanks for helping me and I do understand what you say but I am afraid I have to explain some more details. The contact form is part of a 1 page vertically/horizontally scrolling design. This is why the visitor never should leave the site. Therefore it is set up as an ordinary html page that includes the form with action="mail.php" which is my seperate php file. Within that php file I have that code from the snippet I have posted at the beginning. No I try to figure out what I have to modify where. What in my php file and what in my html file.
Hardy
I don´t want to stretch my luck with you guys too far but maybe you can help me with that.
Hardy
basically, you just need to combine both html and php into single php file and make the form to target itself.
bangbambang
@bangbambang: No, what he wants is to submit the form without leaving that page (i.e. AJAX). Oh, and you forgot the php tags for the closing bracket.
FreekOne
Thanks for trying anyway...enjoy your sunday.
Hardy
A: 

All these answers below are wrong. It will make you occasionally spammed with doubled messages and confuse customers.

Though the solution is kinda tricky

First of all you have to learn the Golden rule:
After processing POST request, your code should redirect a browser using GET method. No exceptions.

Thus, first make it like this

if ($_SERVER['REQUEST METHOD']=='POST') {
  mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader );
  header("Location: ".$_SERVER['PHP_SELF']);
  exit;
}  
// your form goes here

You ought to do it anyway.

Next, if you still want to show this useless message, you have several ways to do it.

  • using GET parameter
  • using cookie
  • ising AJAX.

for example, to use a GET parameter

if ($_SERVER['REQUEST_METHOD']=='POST') {
  mail( $empfaenger, htmlspecialchars( $betreff ), $mailbody, $mailheader );
  header("Location: ".$_SERVER['PHP_SELF']."?thanks");
  exit;
}  
if ($_SERVER['QUERY_STRING']=='thanks') {
  echo 'Thank you for your Email. We will get in touch with you very soon.';
}
// your form goes here
Col. Shrapnel
I have personally been doing it like this since forever, and not once have I had a doubled message. I am intrigued however by what you said in regards to using GET to redirect after processing a POST request. Is this to avoid double posting or is there more to it ?
FreekOne
@FreekOne - basically, if a user hits F5/refresh after a POST request, they'll be prompted to resend the data. User says yes, their data is processed for a second time.
chigley
@Co. Shrapnel<br>Thanks for helping me and I do understand what you say but I am afraid I have to explain some more details. The contact form is part of a 1 page vertically/horizontally scrolling design. This is why the visitor never should leave the site. Therefore it is set up as an ordinary html page that includes the form with action="mail.php" which is my seperate php file. Within that php file I have that code from the snippet I have posted at the beginning. No I try to figure out what I have to modify where. What in my php file and what in my html file.
Hardy
I really have to stay on my site and the visitor should know that his mail was send out and I have to keep it seperate, the php file and the regular html file.
Hardy
@Hardy I don't understand why you're always talking of not leaving your site. What do you call "site"? And what's the reason of leaving it?
Col. Shrapnel
@Hardy, please see my updated answer.
FreekOne
@chigley: Of course, but I find it a lot easier to fix that by simply `unset()` ing all the relevant `$_POST` data after it has been successfully sent. I thought there might be some more to it I didn't know about.
FreekOne
@Col.Shrapnel The site is my website, the designed website that is visited. If someone clicks on "contact" the website will scroll to the contact form. He can fill out the contact form and can hit the send button. Right now, if he is doing this he is leaving my website, he is thrown to a thank you message but he is not on my website anymore. What I want is to keep my html website that contains the form, my seperate php file for the form but when the visitor hits the contact send button I want him to stay on my website. Maybe with a short note, showing I don´t know where, saying "Thank you".
Hardy
@Hardy I can't understand all these sites and websites, sorry. I am not even sure you know where you want to put this "Thank you". You have to make your mind first
Col. Shrapnel
Thank you for helping but I think I have explained as good as I could. It is a simple thing, happens 1000 million times a day. People are visiting a website, clicking on contact, filling out the contact form, clicking send and what happens then is, they will still see the contact form but after clicking the send button, the form is empty and 1 line within the form appears, saying "Thank you". Nothing special, only for me to make that happen.
Hardy