Search code examples
phphtmlcssformsphpmailer

Contact Form Displaying incorrect message after submission: using PHP-mailer


I am new to PHP and would really love some help... I'm banging my head against a wall at this point. All I am trying to do is get a working contact form done... using php-mailer. Emails are coming through as they should, however the problem lies with the the message displayed after clicking submit. As the emails are being sent successfully, the message should read "Your message has been sent to us.", if it doesnt go through the message should read "error, there was an error sending your message." The message after the submission displays the error message no matter what. I tried combing the internet to figure it out to no avail, hopefully you guys can help out. I included the JS, PHP, and Form. Thanks in advance.

<form class="contact-form" action="php/contact-form.php" method="POST">
  <div class="contact-form-success alert alert-success d-none mt-4">
    <strong>Success!</strong> Your message has been sent to us.
  </div>

  <div class="contact-form-error alert alert-danger d-none mt-4">
    <strong>Error!</strong> There was an error sending your message.
    <span class="mail-error-message text-1 d-block"></span>
  </div>
  <!-- ...... -->
</form>


<?php


namespace PortoContactForm;

session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));

header('Content-type: application/json');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'php-mailer/src/PHPMailer.php';
require 'php-mailer/src/SMTP.php';
require 'php-mailer/src/Exception.php';

// Step 1 - Enter your email address below.
$email = 'alex@alexleloup.com';

// If the e-mail is not working, change the debug option to 2 | $debug = 2;
$debug = 1;

// If contact form don't has the subject input change the value of subject here
$subject = ( isset($_POST['subject']) ) ? $_POST['subject'] : 'Define subject in php/contact-form.php line 29';

$message = '';

foreach($_POST as $label => $value) {
    $label = ucwords($label);

    // Use the commented code below to change label texts. On this example will change "Email" to "Email Address"

    // if( $label == 'Email' ) {               
    //  $label = 'Email Address';              
    // }

    // Checkboxes
    if( is_array($value) ) {
        // Store new value
        $value = implode(', ', $value);
    }

    $message .= $label.": " . htmlspecialchars($value, ENT_QUOTES) . "<br>\n";
}

$mail = new PHPMailer(true);

try {

    $mail->SMTPDebug = $debug;                                 // Debug Mode

    // Step 2 (Optional) - If you don't receive the email, try to configure the parameters below:

    //$mail->IsSMTP();                                         // Set mailer to use SMTP
    //$mail->Host = 'mail.alexleloup.com';                     // Specify main and backup server
    //$mail->SMTPAuth = true;                                  // Enable SMTP authentication
    //$mail->Username = '';                    // SMTP username
    //$mail->Password = '';                              // SMTP password
    //$mail->SMTPSecure = 'tls';                               // Enable encryption, 'ssl' also accepted
    //$mail->Port = 587;                                       // TCP port to connect to

    $mail->AddAddress($email);                                 // Add another recipient

    //$mail->AddAddress('person2@domain.com', 'Person 2');     // Add a secondary recipient
    //$mail->AddCC('person3@domain.com', 'Person 3');          // Add a "Cc" address. 
    //$mail->AddBCC('person4@domain.com', 'Person 4');         // Add a "Bcc" address. 

    // From - Name
    $fromName = ( isset($_POST['name']) ) ? $_POST['name'] : 'Website User';
    $mail->SetFrom($email, $fromName);

    // Reply To
    if( isset($_POST['email']) ) {
        $mail->AddReplyTo($_POST['email'], $fromName);
    }

    $mail->IsHTML(true);                                       // Set email format to HTML

    $mail->CharSet = 'UTF-8';

    $mail->Subject = $subject;
    $mail->Body    = $message;

    $mail->Send();
    $arrResult = array ('response'=>'success');

} catch (Exception $e) {
    $arrResult = array ('response'=>'error','errorMessage'=>$e->errorMessage());
} catch (\Exception $e) {
    $arrResult = array ('response'=>'error','errorMessage'=>$e->getMessage());
}

if ($debug == 0) {
    echo json_encode($arrResult);
}
Name:           View - Contact
Written by:     Okler Themes - (http://www.okler.net)
Theme Version:  8.0.0
*/

(function($) {

    'use strict';

    /*
    Custom Rules
    */
    
    // No White Space
    $.validator.addMethod("noSpace", function(value, element) {
        if( $(element).attr('required') ) {
            return value.search(/[a-zA-Z0-9À-žа-яА-ЯёЁα-ωΑ-Ω\s\u0621-\u064A\u0660-\u0669 ]/i) == 0;
        }

        return true;
    }, 'Please fill this empty field.');

    /*
    Assign Custom Rules on Fields
    */
    $.validator.addClassRules({
        'form-control': {
            noSpace: true
        }
    });

    /*
    Contact Form: Basic
    */
    $('.contact-form').each(function(){
        $(this).validate({
            submitHandler: function(form) {

                var $form = $(form),
                    $messageSuccess = $form.find('.contact-form-success'),
                    $messageError = $form.find('.contact-form-error'),
                    $submitButton = $(this.submitButton),
                    $errorMessage = $form.find('.mail-error-message'),
                    submitButtonText = $submitButton.val();

                $submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);

                // Fields Data
                var formData = $form.serializeArray(),
                    data = {};

                $(formData).each(function(index, obj){
                    data[obj.name] = obj.value;
                });

                // Google Recaptcha v2
                if( data["g-recaptcha-response"] != undefined ) {
                    data["g-recaptcha-response"] = $form.find('#g-recaptcha-response').val();
                }

                // Ajax Submit
                $.ajax({
                    type: 'POST',
                    url: $form.attr('action'),
                    data: data
                }).always(function(data, textStatus, jqXHR) {

                    $errorMessage.empty().hide();

                    if (data.response == 'success') {

                        // Uncomment the code below to redirect for a thank you page
                        // self.location = 'thank-you.html';

                        $messageSuccess.removeClass('d-none');
                        $messageError.addClass('d-none');

                        // Reset Form
                        $form.find('.form-control')
                            .val('')
                            .blur()
                            .parent()
                            .removeClass('has-success')
                            .removeClass('has-danger')
                            .find('label.error')
                            .remove();

                        if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
                            $('html, body').animate({
                                scrollTop: $messageSuccess.offset().top - 80
                            }, 300);
                        }

                        $form.find('.form-control').removeClass('error');

                        $submitButton.val( submitButtonText ).attr('disabled', false);
                        
                        return;

                    } else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
                        $errorMessage.html(data.errorMessage).show();
                    } else {
                        $errorMessage.html(data.responseText).show();
                    }

                    $messageError.removeClass('d-none');
                    $messageSuccess.addClass('d-none');

                    if (($messageError.offset().top - 80) < $(window).scrollTop()) {
                        $('html, body').animate({
                            scrollTop: $messageError.offset().top - 80
                        }, 300);
                    }

                    $form.find('.has-success')
                        .removeClass('has-success');
                        
                    $submitButton.val( submitButtonText ).attr('disabled', false);

                });
            }
        });
    });

    /*
    Contact Form: Advanced
    */
    $('#contactFormAdvanced').validate({
        onkeyup: false,
        onclick: false,
        onfocusout: false,
        rules: {
            'captcha': {
                captcha: true
            },
            'checkboxes[]': {
                required: true
            },
            'radios': {
                required: true
            }
        },
        errorPlacement: function(error, element) {
            if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
                error.appendTo(element.closest('.form-group'));
            } else {
                error.insertAfter(element);
            }
        }
    });

    /*
    Contact Form: reCaptcha v3
    */
    $('.contact-form-recaptcha-v3').each(function(){
        $(this).validate({
            submitHandler: function(form) {

                var $form = $(form),
                    $messageSuccess = $form.find('.contact-form-success'),
                    $messageError = $form.find('.contact-form-error'),
                    $submitButton = $(this.submitButton),
                    $errorMessage = $form.find('.mail-error-message'),
                    submitButtonText = $submitButton.val();

                $submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);

                var site_key = $('#google-recaptcha-v3').attr('src').split("render=")[1];
                grecaptcha.execute(site_key, {action: 'contact_us'}).then(function(token) {

                    // Fields Data
                    var formData = $form.serializeArray(),
                        data = {};

                    $(formData).each(function(index, obj){
                        data[obj.name] = obj.value;
                    });

                    // Recaptcha v3 Token
                    data["g-recaptcha-response"] = token;

                    // Ajax Submit
                    $.ajax({
                        type: 'POST',
                        url: $form.attr('action'),
                        data: data
                    }).always(function(data, textStatus, jqXHR) {

                        $errorMessage.empty().hide();

                        if (data.response == 'success') {

                            // Uncomment the code below to redirect for a thank you page
                            // self.location = 'thank-you.html';

                            $messageSuccess.removeClass('d-none');
                            $messageError.addClass('d-none');

                            // Reset Form
                            $form.find('.form-control')
                                .val('')
                                .blur()
                                .parent()
                                .removeClass('has-success')
                                .removeClass('has-danger')
                                .find('label.error')
                                .remove();

                            if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
                                $('html, body').animate({
                                    scrollTop: $messageSuccess.offset().top - 80
                                }, 300);
                            }

                            $form.find('.form-control').removeClass('error');

                            $submitButton.val( submitButtonText ).attr('disabled', false);
                            
                            return;

                        } else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
                            $errorMessage.html(data.errorMessage).show();
                        } else {
                            $errorMessage.html(data.responseText).show();
                        }

                        $messageError.removeClass('d-none');
                        $messageSuccess.addClass('d-none');

                        if (($messageError.offset().top - 80) < $(window).scrollTop()) {
                            $('html, body').animate({
                                scrollTop: $messageError.offset().top - 80
                            }, 300);
                        }

                        $form.find('.has-success')
                            .removeClass('has-success');
                            
                        $submitButton.val( submitButtonText ).attr('disabled', false);

                    });

                });
            }
        });
    });

}).apply(this, [jQuery]);


Solution

  • The issue seems to be that near the top of your PHP script you are setting:

    $debug = 1;

    Then at the end you say:

    if ($debug == 0) {
        echo json_encode($arrResult);
    }
    

    Which results in the script not sending any response, or at least not the {"'response": "success"} json you expect which then causes this js check to fail:

    if (data.response == 'success')
    

    You'll need to either set $debug = 0;, remove the if ($debug == 0) check, or otherwise resolve this logic issue.