1

I'm a bit of a newbie and I'm trying to code a contact form for a website that will then send an email to my personal account.

I want to receive an AJAX response when calling PHPMailer, so that I can display an alert saying 'You sent the email' or 'Email failed'. However, I think that I'm not leaving enough time between executing the code and waiting for the response. As I can send emails, but I keep getting this message in the developer panel:

enter image description here

Here is my HTML:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <section>
        <div class="row vh-100 vw-100 justify-content-center" id="contact">
            <div class="row w-100 buffer snow4"></div>
            <div class="row w-100 justify-content-center mt-3 snow4">
                <div>
                    <h3>Contact</h3>
                </div>
            </div>
            <div class="row justify-content-center w-100 mt-5 snow4">
                <div class="contact_form">
                    <div class="contact-image">
                        <i class="fas fa-mountain"></i>
                    </div>
                    <div class="row w-100 buffer"></div>
                    <div id="contact_alert" class="alert alert-danger alert-dismissible fade show" role="alert" style="display: none;">
                        <strong>Error!</strong> Please fill out the form correctly.
                        <button type="button" class="close" onclick="hideAlert();" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <form id="contact-form" class="form-horizontal" method="post">
                        <div class="row">
                            <div class="col-6">
                                <div class="form-group row">
                                    <input type="text" class="form-control m-2" id="form-name" name="form-name" placeholder="Name" required>
                                </div>
                                <div class="form-group row">
                                    <input type="email" class="form-control m-2" id="form-email" name="form-email" placeholder="Email" required>
                                </div>
                                <div class="form-group row">
                                    <input type="tel" class="form-control m-2" id="form-phone" name="form-phone" placeholder="Mobile number" required>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="form-group row">
                                    <input type="text" class="form-control m-2" id="form-subject" name="form-subject" placeholder="Subject" required>
                                </div>
                                <div class="form-group row">
                                    <textarea style="height: 110px;" class="form-control m-2" rows="3" id="form-message" name="form-message" placeholder="Write something..." required></textarea>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-group">
                                    <button class="btn btn-outline-secondary" onclick="sendMail()">Send Message!</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="row vw-100 justify-content-between" id="footer">
                <div>Laura Dennis &#169 2021</div>
                <a class="font font2" data-toggle="modal" data-target="#exampleModal"><i class="far fa-envelope"></i></a>
                <a class="font" href="https://github.com/Dennis-debug" target="_blank"><i class="fab fa-github"></i></a>
                <a class="font" href="https://www.linkedin.com/in/lauradennis01/" target="_blank"><i class="fab fa-linkedin"></i></a>
            </div>
        </div>
    </section>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://d3js.org/d3.v4.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <script src="vendor/js/fontawesomeall.min.js"></script>
    <script src='main.js'></script>
</body>
</html>

Here is my JavaScript:

function isNotEmpty(caller) {
    if (caller == "") {
        $('#contact_alert').css('display', 'block');
        return false;
    } else {
        return true;
    }
}

function sendMail() {
    var name = $('#form-name').val();
    var email = $('#form-email').val();
    var phone = $('#form-phone').val();
    var subject = $('#form-subject').val();
    var message = $('#form-message').val();

    if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(phone) && isNotEmpty(subject) && isNotEmpty(message)) {
        $.ajax({
            type: "POST",
            url: "sendMail.php",
            data: {
                name: name,
                email: email,
                phone: phone,
                subject: subject,
                message: message
            },
            success: function (data) { console.log(data); },
            dataType: "json",
            contentType: "application/json"
        })
    }
}

Here is my PHP:

<?php

$executionStartTime = microtime(true) / 1000;

//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader
require 'vendor/autoload.php';

//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'smtp.gmail.com';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = MY EMAIL;      //SMTP username
    $mail->Password   = MY PASSWORD;                      //SMTP password
    $mail->SMTPSecure = 'ssl';                                  //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 465;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    //Recipients
    $mail->setFrom(MY EMAIL, 'Mailer');
    $mail->addAddress(MY EMAIL2, 'Laura Dennis');
    //$mail->addReplyTo($_POST['email'], $_POST['name']);

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'hello';
    $mail->Body    = 'hello';

    $mail->send();

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
    $output['data'] = [];

    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output);

} catch (Exception $e) {

    $output['status']['code'] = "400";
    $output['status']['name'] = "executed";
    $output['status']['description'] = "query failed";  
    $output['data'] = [];

    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output);
}

?>

  • What is the error in the network tab? Is it a 500 server error? Have you turned on PHP error reporting? That will likely tell you where the issue is. https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display – Kinglish May 06 '21 at 15:57
  • 2
    There is [an example of doing this in vanilla JS included with PHPMailer](https://github.com/PHPMailer/PHPMailer/blob/master/examples/contactform-ajax.phps). Also bear in mind that PHPMailer's SMTP debug output is not valid JSON, and will confuse the responses, so you may need to turn that off. Iit's a good idea to test your PHP code separately from your JS, otherwise you're trying to debug two things that may be interfering with each other, making it much more difficult. – Synchro May 06 '21 at 16:18

0 Answers0