简体   繁体   中英

Get a success message on same page after form submit / PHP AJAX

I'm trying to config a contact form based on php/ajax to a website, but I can't manage to add a "success" message after the form is submitted. I receive the email correctly if I keep the "action" parameter to the php file inside form tag, but the page gets redirected to the blank php page. However, if I remove the link, the email is not sent.

I've tried in the past hours many of the suggestions I found online, but I can't manage to make it work properly. Any guesses?

Thanks

HTML

    <form id="contact-form" method="POST" action="simple-email-form-v1/form-to-email.php">

        <div class="control-group">
            <label>Your Name</label>
            <input class="fullname" type="text" name="fullname" />
        </div>

        <div class="control-group">
            <label>Email</label>
            <input class="email" type="text" name="email" />
        </div>

        <div class="control-group">
            <label>Phone (optional)</label>
            <input class="phone" type="text" name="phone" />
        </div>

        <div class="control-group">
            <label>Message</label>
            <textarea class="message" name="message"></textarea>
        </div>

        <div id="errors"></div>

        <div class="control-group no-margin">
            <input type="submit" name="submit" value="Submit" id="submit" />
        </div>

    </form>
</div>

PHP

   <?php
/*
Configuration 
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.

*/

$email_recipients = "abcde@gmail.com";//<<=== enter your email address here
//$email_recipients =  "mymanager@gmail.com,his.manager@yahoo.com"; <<=== more than one recipients like this


$visitors_email_field = 'email';//The name of the field where your user enters their email address
                                        //This is handy when you want to reply to your users via email
                                        //The script will set the reply-to header of the email to this email
                                        //Leave blank if there is no email field in your form
$email_subject = "New Form submission";

$enable_auto_response = true;//Make this false if you donot want auto-response.

//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi

Thanks for contacting us. We will get back to you soon!

Regards
Your website
";

$referer = $_SERVER['HTTP_REFERER'];


/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
    // note that our submit button's name is 'submit' 
    // We are checking whether submit button is pressed
    // This page should not be accessed directly. Need to submit the form.
    echo "error; you need to submit the form!".print_r($_POST,true);
    exit;
}

require_once "includes/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
    echo "<B>Validation Errors:</B>";

    $error_hash = $validator->GetErrors();
    foreach($error_hash as $inpname => $inp_err)
    {
        echo "<p>$inpname : $inp_err</p>\n";
    }
    exit;
}

$visitor_email='';
if(!empty($visitors_email_field))
{
    $visitor_email = $_POST[$visitors_email_field];
}

if(empty($email_from))
{
    $host = $_SERVER['SERVER_NAME'];
    $email_from ="forms@$host";
}

$fieldtable = '';
foreach ($_POST as $field => $value)
{
    if($field == 'submit')
    {
        continue;
    }
    if(is_array($value))
    {
        $value = implode(", ", $value);
    }
    $fieldtable .= "$field: $value\n";
}

$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";

$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";

$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
@mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);

//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
    $headers = `enter code here`"From: $email_from \r\n";
    @mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}

//done. 

if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}


?>

JS

    $(document).ready(function () {

    $("#contact-form").validate({
        rules: {
            fullname: {
                required: true
            },
            email: {
                required: true,
                email: true
            },
            message: {
                required: true,
                maxlength: 8000
            }
        },

        messages: { // custom messages
            fullname: {
                required: "Por favor, insira seu nome"
            },
            email: {
                required: "Por favor, insira seu email"
            },
            message: {
                required: "Por favor, insira sua mensagem",
                maxlength: jQuery.format("The maxlength for message is {0} !")
            },
        },

        submitHandler: function(form) {
            $form = $(form);
            $container = $form.parent();
            w = $form.outerWidth();
            h = $form.outerHeight();
            $form.hide();

            $('#msg_submitting', $container).width(w).height(h).fadeIn(1000);            
            $.ajax({
                type: "POST",
                url: $form.attr('action'),
                data: $form.serialize(),
                success: function (data) {
                       $("#mail-status").html(data);
        },
        error:function (){}
        });

            return false;

        }

    });

});

Where is the "mail-status" id in html? You can replace "mail-status" with "errors".

The issue is there is no "mail-status" id in a page, so it is not displaying response on that div.

Define "mail-status" on html or just replace "mail-status" with "errors", as your html contains .

Put the <div id="errors"></div> outside the form element. When you are hiding the form the <div id="errors"></div> also gets hidden hence you cannot see anything.

<form id="contact-form" method="POST" action="header.php">

      <div class="control-group">
          <label>Your Name</label>
          <input class="fullname" type="text" name="fullname" />
      </div>

      <div class="control-group">
          <label>Email</label>
          <input class="email" type="text" name="email" />
      </div>

      <div class="control-group">
          <label>Phone (optional)</label>
          <input class="phone" type="text" name="phone" />
      </div>

      <div class="control-group">
          <label>Message</label>
          <textarea class="message" name="message"></textarea>
      </div>


      <div class="control-group no-margin">
          <input type="submit" name="submit" value="Submit" id="submit" />
      </div>

  </form>
  <div id="errors"></div>

Also in the php file you need to echo $message; so that it should be available in the ajax data param.

if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
    $message = "Success!";
} else {
    $message = "Erro!";
}
echo $message;

First, add this element to the html :

<div id="mail-status"></div>

Then add preventDefault() to the js to prevent the form from submitting :

<script>

$(document).ready(function () {

    $("#contact-form").submit(function(e) {
        e.preventDefault(); // added preventDefault()
    }).validate({
        rules: {
            fullname: {
                required: true
            },
            email: {
                required: true,
                email: true
            },
            message: {
                required: true,
                maxlength: 8000
            }
        },

        messages: { // custom messages
            fullname: {
                required: "Por favor, insira seu nome"
            },
            email: {
                required: "Por favor, insira seu email"
            },
            message: {
                required: "Por favor, insira sua mensagem",
                maxlength: jQuery.format("The maxlength for message is {0} !")
            },
        },

        submitHandler: function (form) {
            $form = $(form);
            $container = $form.parent();
            w = $form.outerWidth();
            h = $form.outerHeight();

            $('#msg_submitting', $container).width(w).height(h).fadeIn(1000);
            $.ajax({
                type: "POST",
                url: $form.attr('action'),
                data: $form.serialize(),
                success: function (data) {
                    $("#mail-status").html(data);
                },
                error: function () {}
            });
            $form.hide(); // moved below ajax call

            return false;

        }

    });

});

</script>

Then don't forget to add echo statement to the php :

if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
    $message = "Success!";
} else {
    $message = "Erro!";
}

echo $message;

Perhaps this might help you:

<div id="mail-status"></div>
<form id="contact-form" method="POST" action="simple-email-form-v1/form-to-email.php">

Perhaps the way you handle the submit is causing the page to redirect?

Change your button type submit to a button . See below,

<input type="button" name="submit" value="Submit" id="submit" />

Then, target the button click for the form submission, like this,

$(document).ready(function () {
     $('#submit').click(function(){
         //do you logic here
     });
});

When changing the button type to be a button , you don't need to worry about preventDefault() for submission, because submission only happens through through Ajax / JS.

Hope this helps.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM