Form ajax submission and validation with php mailer

PHOTO EMBED

Wed Feb 28 2024 10:22:57 GMT+0000 (Coordinated Universal Time)

Saved by @roshan1995 #html #php #javascript

<!--HTML Code-->
  
  <form id="contact_form" method="post">
    <div class="row">
        <div class="col-md-12 form-group g-mb-20">
            <input type="text" class="form-control" id="txtContactName" name="txtContactName" placeholder="Full Name" tabindex="201" required>
            <div class="error-message" id="txtContactName-error"></div>
        </div>

        <div class="col-md-12 form-group g-mb-20">
            <input type="email" class="form-control" id="txtContactEmail" name="txtContactEmail" placeholder="Email Address" tabindex="202" required>
            <div class="error-message" id="txtContactEmail-error"></div>
        </div>

        <div class="col-md-12 form-group g-mb-20">
            <input type="text" class="form-control" id="txtContactPhone" name="txtContactPhone" placeholder="Contact Number" maxlength="10" tabindex="203" required>
            <div class="error-message" id="txtContactPhone-error"></div>
        </div> 

        <div class="col-md-12 form-group g-mb-40">
            <textarea class="form-control" id="txtContactMessage" name="txtContactMessage" rows="7" placeholder="Message" maxlength="160" tabindex="204" required></textarea>
            <div class="error-message" id="txtContactMessage-error"></div>
        </div>
    </div>
    <input type="submit" class="btn btn-lg u-btn-primary g-font-weight-600 g-font-size-default rounded-0 text-uppercase g-py-15 g-px-30" id="btnContactSubmit" name="btnContactSubmit" value="SUBMIT">
</form>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script>
	
</script>
<script>
    $(document).ready(function() {
        $('#contact_form').validate({
            rules: {
                txtContactName: "required",
                txtContactEmail: {
                    required: true,
                    email: true
                },
                txtContactPhone: {
                    required: true,
                    digits: true,
                    maxlength: 10
                },
                txtContactMessage: "required"
            },
            messages: {
                txtContactName: "Please enter your full name",
                txtContactEmail: {
                    required: "Please enter your email address",
                    email: "Please enter a valid email address"
                },
                txtContactPhone: {
                    required: "Please enter your contact number",
                    digits: "Please enter only digits",
                    maxlength: "Please enter a valid 10-digit phone number"
                },
                txtContactMessage: "Please enter your message"
            },
            errorPlacement: function(error, element) {
                error.appendTo(element.closest('.form-group').find('.error-message'));
            },
            submitHandler: function(form) {
                var formData = $(form).serialize();
                $.ajax({
                    type: 'POST',
                    url: 'mail.php',
                    data: formData,
                    success: function(response) {
                        $('#contact_form').append('<div class="success-message" style="color: green;">Message sent successfully!</div>');
                        setTimeout(function() {
                            $('#contact_form')[0].reset();
                        }, 4000);
                    },
                    error: function(xhr, status, error) {
                        console.error(xhr.responseText);
                        alert('Error: ' + xhr.responseText);
                    }
                });
            }
        });
    });
</script>

PHP Miler folder should be there
Create folder name with mail.php and add below code there 
<?php
// Include PHPMailer autoload file

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

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

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST['txtContactName'];
    $email = $_POST['txtContactEmail'];
    $phone = $_POST['txtContactPhone'];
    $message = $_POST['txtContactMessage'];

    // Initialize PHPMailer
    $mail = new PHPMailer(true);
    try {
        // SMTP settings
		$mail->IsSMTP();        // Sets Mailer to send message using SMTP
		$mail->SMTPAuth = true; // Authentication enabled
		$mail->SMTPSecure = 'tls'; // Secure transfer enabled REQUIRED for Gmail
		$mail->Host = 'smtp-relay.brevo.com';
		$mail->Port = 587;
		$mail->Username = 'advanceindiaprojectltd@gmail.com';
		$mail->Password = 'xsmtpsib-e66045ab99d2f28608d548ca33a5a3ac8cc14a6896d682cbdc5418c80154b5eb-6B5QJOyT18GvbzmZ';
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);

        // Recipients
        $mail->setFrom($email, $name);
        $mail->addAddress('roshan@teamvariance.com'); // Add recipient email address

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Contact Form Submission';
		// Construct HTML table for the email body
        $message = '
            <h3 align="center">Details</h3>
            <table border="1" width="100%" cellpadding="5" cellspacing="5">
                <tr>
                    <td width="30%">Name</td>
                    <td width="70%">' . $name . '</td>
                </tr> 
                <tr>
                    <td width="30%">Email</td>
                    <td width="70%">' . $email . '</td>
                </tr>
                <tr>
                    <td width="30%">Phone</td>
                    <td width="70%">' . $phone . '</td>
                </tr>
                <tr>
                    <td width="30%">Message</td>
                    <td width="70%">' . $message . '</td>
                </tr>
            </table>
        ';
        $mail->Body = $message;

        // Send email
        $mail->send();
        
        // Return success message
        echo "success";
    } catch (Exception $e) {
        // Return error message
        echo "error";
    }
}
?>



content_copyCOPY