6

I don't code in PHP, but I have this form which I pulled off the web and its working great:

What I would like to do is somehow add some code in here that can fire up a JS script, simple alert box, saying "Thank you form is submitted". After the form was received by this mailer.php file.

<?php
if(isset($_POST['submit'])) {

$to = "[email protected]";
$subject = "Form Tutorial";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];

$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";

echo "Data has been submitted to $to!";
mail($to, $subject, $body);

} else {

echo "blarg!";

}
?>
2
  • 2
    LOL @ the descriptive error message... it is PHP, after all. Commented Oct 22, 2009 at 22:57
  • 1
    Note: just because you can use an alert box doesn't mean you should. Commented Oct 22, 2009 at 23:22

3 Answers 3

22

instead of:

echo "Data has been submitted to $to!";

just

echo '<script type="text/javascript">alert("Data has been submitted to ' . $to . '");</script>';
Sign up to request clarification or add additional context in comments.

Comments

6

You can echo Javascript in a <script></script> block in your PHP. The browser will then execute it.

So for example:

<?php
     echo "<script language='javascript'>alert('thanks!');</script>"; 
?>

Comments

3

You just need to output the HTML/JS. Something like this:

<?php
    if(isset($_POST['submit'])) {
        $to = "[email protected]";
        $subject = "Form Tutorial";
        $name_field = $_POST['name'];
        $email_field = $_POST['email'];
        $message = $_POST['message'];

        $body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";

        mail($to, $subject, $body);
        echo "<script type=\"text/javascript\">alert('Thank you form is submitted');</script>";
    } else {
        echo "blarg!";
    }
?>

alternatively:

<?php
    if(isset($_POST['submit'])) {
        $to = "[email protected]";
        $subject = "Form Tutorial";
        $name_field = $_POST['name'];
        $email_field = $_POST['email'];
        $message = $_POST['message'];

        $body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";

        mail($to, $subject, $body);
?>
    <script type="text/javascript">alert('Thank you form is submitted.');</script>
<?php
    } else {
        echo "blarg!";
    }
?>

However, it sounds like you maybe don't want to have the page reload between submitting the form and giving the user the confirmation. For that you'd need to submit the form via AJAX. I recommend looking into JQuery. It makes this easy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.