0

I have a simple POST script for PHP which sends an email, but when I click the submit button it executes and then goes to the script directory (ex: localhost/sendMail/test.php). Is it possible to post an alert box, and then stay on the page instead of going to the script and then redirecting back onto the submit page?

This is my script.

<?php
$subject = 'Your website: Contact'; // Subject of your email
$to = 'myemail';  // Enter recipient's E-mail address
$emailTo = $_REQUEST['email'];

$headers = "MIME-Version: 1.1";
$headers .= "Content-type: text/html; charset=iso-8859-1";
$headers .= "From: " . $emailTo . "\r\n"; // Sender's E-mail
$headers .= "Return-Path:". $emailTo;

$body = 'You have received a new inquiry!' . "\n\n";
$body .= 'Name: ' . $_REQUEST['name'] . "\n";
$body .= 'Email: ' . $_REQUEST['email'] . "\n";
$body .= 'Phone: ' . $_REQUEST['phone'] . "\n\n";
$body .= 'Message: ' . $_REQUEST['message'];

if($_REQUEST['name'] != "" && $_REQUEST['email'] != "" && $_REQUEST['phone'] != "" && $_REQUEST['message'] != "")
{
    if (@mail($to, $subject, $body, $headers))
    {
        // Transfer the value 'sent' to ajax function for showing success message.
        echo 'sents';
    }
    else
    {
        // Transfer the value 'failed' to ajax function for showing error message.
        echo 'failed';
    }
}
else
{
    $message = "Invalid fields!";
    echo "<script type='text/javascript'>alert('$message');</script>";
    //header("Location: http://localhost/abtek/contact.html");
    exit;
}
?>

So when the alert is executed, is it possible to stop it from going to the script, and instead staying on the page until the fields are all valid to submit? As well as when they are submitted to display an alert again and stay on the page instead of doing a bunch of redirects.

Any help would be greatly appreciated.

2 Answers2

0

You can submit the form with ajax/jquery and stop the redirect. See here: Stackoverflow

Community
  • 1
  • 1
VikingBlooded
  • 884
  • 1
  • 6
  • 17
0

You can use jQuery, like this:

$('#my-submit').on('click', function(e){
    e.preventDefault(); // prevents regular form submission
    $.ajax({
        url: 'localhost/sendMail/test.php',
        data: $('form').serialize(),
        success: function(result){
            alert('Message: ' + result );
        },
        error: function(err){
           alert(err)
        }
    })
});

In your PHP you should just do echo $message; to handle error better. Read all you can about jQuery/AJAX, as there are important options you can explode, like using JSON.

aesede
  • 5,541
  • 2
  • 35
  • 33