简体   繁体   中英

How do I show php error message when I'm submitting the form asynchronously?

I'm using phpMailer to send the email with AJAX.

So what I need to do is send the mail and have the error messages from submit.php and display it on contact.php

At the moment every submission displays. Message sent even if it really hasn't.

contact.php

    <div class="contact-form">
        <div class="container">
            <h2>We'd love to hear from you.</h2>
            <p>Get in touch and lets kickstart your project!</p>
            <form action="/submit" method="post" class="form">
                <label>
                <input type="text" name="name" placeholder="Name">
                </label>
                <label>
                <input type="text" name="company" placeholder="Company">
                </label>
                <label>
                  <input type="text" name="phone" placeholder="Phone">
                </label>
                <label>
                  <input type="text" name="email" placeholder="Email" required>
                </label>
                <label>
                  <textarea name="message" placeholder="Tell us about your project!" required></textarea>
                </label>
                <input class="submit" type="submit" value="Submit">
                <div id="loader"></div>
                <span class="sent">Your message has been sent!</span>
                <span class="not-sent">Your message has been sent!</span>
            </form> 
        </div>
    </div>


    <script> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
            // bind 'myForm' and provide a simple callback function 
            $('.form').ajaxForm(function() { 

            }); 
        }); 

    $(document).ready(function(){
        var $loading = $('#loader').hide();
        $(document)
          .ajaxStart(function () {
            $loading.show();
          })
          .ajaxStop(function () {
            $loading.hide();
          });
    }); 

    $(document).ready(function(){
        var $loading = $('.sent').hide();
        $(document)
          .ajaxStart(function () {
            $loading.hide();
          })
          .ajaxStop(function () {
            $loading.show();
          });
    });

    $(document).ready(function(){
        var $loading = $('.submit').show();
        $(document)
          .ajaxStart(function () {
            $loading.hide();
          })
          .ajaxStop(function () {
            $loading.show();
          });
    });

    </script> 

submit.php

    <?php
    require 'libs/phpmailer/PHPMailerAutoload.php';

    $mail = new PHPMailer;


    $name = $_POST['name'];
    $company = $_POST['company'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'mail.metalink.co.za';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'info@website.com';                 // SMTP username
    $mail->Password = 'pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 25;                                    // TCP port to connect to

    $mail->From = $email = $_POST['email'];
    $mail->FromName = $name = $_POST['name'];
    $mail->addAddress('info@website.com', 'website');     // Add a recipient
    $mail->addReplyTo($email = $_POST['email']);

    $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
    $mail->isHTML(true);                                  // Set email format to HTML

    $mail->Subject = 'Website Response Form';
    $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
    $mail->Body =    "<span><p><strong>Name - </strong> {$name} </p></span>
                      <p><strong>Company - </strong> {$company} </p>
                      <p><strong>Phone - </strong> {$phone} </p>
                      <p><strong>Email - </strong> {$email} </p>
                      <p><strong>Message - </strong> {$message} </p>";


    if(!$mail->send()) {
        echo '<span class="not-sent">Invalid Email</span>';
        //echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo '<span class="sent">Your message has been sent!</span>';
    }
    ?>

You need to generate a response that JS can parse. This is a simple example. You should also look into setting the right content type and response code.

if(!$mail->send()) {
    echo json_encode([
        'success' => false,
        'message' => "Invalid Email"
    ]);
    //echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo json_encode([
        'success' => true,
        'message' => "Your message has been sent!"
    ]);
}

You should then be able to parse this response in JS using the callback method.

$('.form').ajaxForm(function(callback) { 
    console.log(callback);
}); 

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