
Formulario de contacto en PHP, SMTP y Ajax
Este es un formulario de contacto en PHP y AJAX hace uso de SMTP para enviar el mensajes, además tiene un código captcha independiente, los campos o inputs esta validados correctamente, puedes descargar el formulario de contacto al finalizar del artículo.

En la estructura index.html
se encuentra el contenido principal del formulario, las hojas de estilos se encargan de darle ese diseño, la estructura del archivos javascript main.js
se encargan de la validación de cada uno de los campos.
/* -------------------------------------------------------------------
* Plugin Name : PHP Ajax Contact Form
* Author Name : anthoncode
* Author URI : https://anthoncode.com
* File Name : style.css
------------------------------------------------------------------- */
/* -------------------------------------------------------------------
[Table of contents]
* 01.Contact Form
*/
(function($) {
"use strict";
// Call all ready functions
// Llamar a todas las funciones listas
conformy_contactForm();
})(window.jQuery);
/* ------------------------------------------------------------------- */
/* 02.Contact Form
/* ------------------------------------------------------------------- */
function conformy_contactForm() {
"use-strict";
// Validate Input Variables
// Validar variables de entrada
var contactEmail = $("#contactEmail");
var contactPhone = $("#contactPhone");
var formControl = $('.contact-form-group .form-control');
// Added AutoComplete Attribute Turned Off
// Atributo de Autocompletar agregado desactivado
formControl.attr("autocomplete","off");
// Email Validation
// Validación de correo electrónico
contactEmail.on("keyup", function() {
var emailInputValue = $(this).val().trim();
if (emailInputValue.length > 0) {
let validate = $(this).conformyEmailValidate();
if (!validate === true) {
$(this).parent().find("span").removeClass("success").addClass("error");
} else {
$(this).parent().find("span").removeClass("error").addClass("success");
}
}else{
$(this).parent().find("span").removeAttr("class");
}
});
// Phone Validation
// Validación de teléfono
contactPhone.on("keyup", function() {
var phoneInputValue = $(this).val().trim();
if (phoneInputValue.length > 0) {
let validate = $(this).conformyPhoneValidate();
if (!validate === true) {
$(this).parent().find("span").removeClass("success").addClass("error");
} else {
$(this).parent().find("span").removeClass("error").addClass("success");
}
}else{
$(this).parent().find("span").removeAttr("class");
$(this).parent().find("span").addClass("error");
}
});
// Form Control Validate
// Validar control de formulario
$(".form-control:not('#contactEmail,#contactPhone')").on("keyup", function() {
var formInputValue = $(this).val().trim();
if (formInputValue.length > 0) {
$(this).parent().find("span").removeClass("error").addClass("success");
}else {
$(this).parent().find("span").removeAttr("class");
$(this).parent().find("span").addClass("error");
}
});
// Popup Variables
let termsAgree = $('#termsAgree');
// Terms Agree
// Términos de acuerdo
termsAgree.on("click",function(event){
$("#termsCheckBox").prop("checked",true);
});
// Captcha Variables
let textCaptcha = $("#txtCaptcha");
let textCaptchaSpan = $('#txtCaptchaSpan');
let textInput = $('#txtInput');
// Generates the Random number function }
// Genera la función de número aleatorio
function randomNumber(){
let a = Math.ceil(Math.random() * 9) + '',
b = Math.ceil(Math.random() * 9) + '',
c = Math.ceil(Math.random() * 9) + '',
d = Math.ceil(Math.random() * 9) + '',
e = Math.ceil(Math.random() * 9) + '',
code = a + b + c + d + e;
textCaptcha.val(code);
textCaptchaSpan.html(code);
}
// Called random number function
// Función llamada número aleatorio
randomNumber();
// Validate the Entered input aganist the generated security code function
// Validar la entrada ingresada junto con la función del código de seguridad generado
function validateCaptcha() {
let str1 = textCaptcha.val();
let str2 = textInput.val();
if (str1 == str2) {
return true;
} else {
return false;
}
}
// Form Conttrol Captcha Validate
// Formulario Conttrol Captcha Validar
textInput.on("keyup", function() {
if (validateCaptcha() == true) {
$(this).parent().find("span").removeClass("error").addClass("success");
}else {
$(this).parent().find("span").removeAttr("class");
$(this).parent().find("span").addClass("error");
}
});
// Contact Form Submit
// Formulario de contacto Enviar
$("#contactForm").on("submit", function(event) {
///var $this = $(this);
// Contact Form Input Value
// Valor de entrada del formulario de contacto
let $this = $(this);
let name = $("#contactName").val().trim();
let email = $("#contactEmail").val().trim();
let phone = $("#contactPhone").val().trim();
let subject = $("#contactSubject").val().trim();
let message = $("#contactMessage").val().trim();
let termsCheckBox = $("#termsCheckBox").prop("checked");
let validateEmail = $("#contactEmail").conformyEmailValidate();
let validatePhone = $("#contactPhone").conformyPhoneValidate();
let selectedNull = $('#contactSubject').find("option").eq(0).val();
if (name =='' || email =='' || phone == '' || message == '' || textInput == '') {
$(this).parent().find("span").addClass("error");
if($('.empty-form').css("display") == "none"){
$('.empty-form').stop().slideDown().delay(3000).slideUp();
}else {
return false;
}
} else if (subject == selectedNull) {
if($('.subject-alert').css("display") == "none"){
$('.subject-alert').stop().slideDown().delay(3000).slideUp();
}else {
return false;
}
} else if (termsCheckBox == false) {
if($('.terms-alert').css("display") == "none"){
$('.terms-alert').stop().slideDown().delay(3000).slideUp();
}else {
return false;
}
} else if (!validatePhone === true) {
$("#contactPhone").parent().find("span").removeClass("success").addClass("error");
if($('.phone-invalid').css("display") == "none"){
$('.phone-invalid').stop().slideDown().delay(3000).slideUp();
}else {
return false;
}
} else if (!validateEmail === true) {
$("#contactEmail").parent().find("span").removeClass("success").addClass("error");
if($('.email-invalid').css("display") == "none"){
$('.email-invalid').stop().slideDown().delay(3000).slideUp();
}else {
return false;
}
} else if (validateCaptcha() != true){
$("#textInput").parent().find("span").removeClass("success").addClass("error");
if($('.security-alert').css("display") == "none"){
$('.security-alert').stop().slideDown().delay(3000).slideUp();
}else {
return false;
}
} else {
$this.find(':submit').append('<span class="fas fa-spinner fa-pulse ml-3"></span>');
$this.find(':submit').attr('disabled','true');
$.ajax({
url: "assets/vendor/send_mail.php?mail=request",
data: {
contact_name: name,
contact_email: email,
contact_phone: phone,
contact_subject: subject,
contact_message: message
},
type: "POST",
success: function(response) {
$(".form-control").parent().find("span").removeAttr("class");
$("#contactForm")[0].reset();
$(".select-selected").html(selectedNull);
if (response == true) {
$this.find(':submit').removeAttr('disabled');
$this.find(':submit').find("span").fadeOut();
$("#formSuccessModal").modal("show");
// Called random number function
// Función llamada número aleatorio
randomNumber();
} else {
$this.find(':submit').removeAttr('disabled');
$this.find(':submit').find("span").fadeOut();
$("#formDangerModal").modal("show");
$("#formDangerModal #error_message").html(response);
// Called random number function
// Función llamada número aleatorio
randomNumber();
}
}
});
}
event.preventDefault();
});
}
El archivo send_mail.php
se encarga de enviar el mensaje del formulario a través de SMTP, es necesario configurar el SMTP en smtp_host, smtp_port (línea 52), smtp_username, smtp_password y la dirección de correo en la línea 72.
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
// Importar clases de PHPMailer al espacio de nombres globales
// Estos deben estar en la parte superior de su script, no dentro de una función
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
// Cargar el cargador automático de Composer
require 'autoload.php';
if (isset($_GET['mail'])) {
#Cleaning Html,Script Tags and special characters
# Limpieza de HTML, etiquetas de script y caracteres especiales
function postTextClean($text) {
$text = trim(addslashes(htmlspecialchars(strip_tags($_POST[$text]))));
return $text;
}
function getTextClean($text) {
$text = trim(addslashes(htmlspecialchars(strip_tags($_GET[$text]))));
$search = array('Ç','ç','Ğ','ğ','ı','İ','Ö','ö','Ş','ş','Ü','ü');
$replace = array('c','c','g','g','i','i','o','o','s','s','u','u');
$new_text = str_replace($search,$replace,$text);
return $new_text;
}
$getActionURI = getTextClean('mail');
if($getActionURI ==="request") {
#Let's get the data from the form
$contact_name = postTextClean('contact_name');
$contact_email = postTextClean('contact_email');
$contact_subject = postTextClean('contact_subject');
$contact_phone = postTextClean('contact_phone');
$contact_message = postTextClean('contact_message');
$mail_content = "<h2>From</h2>
<p>{$contact_email}</p>
<h2>Name</h2>
<p>{$contact_name}</p>
<h2>Phone</h2>
<p>{$contact_phone}</p>
<h2>Subject</h2>
<p>{$contact_subject}</p>
<h2>Message</h2>
<p>".nl2br($contact_message)."</p>";
// Hosting SMTP Settings
$smtp_host = 'smtp.example.com'; // Enter the smtp server address you got from your hosting here
$smtp_port = 587; // TCP port to connect to
$smtp_username = 'user@example.com'; // SMTP username
$smtp_password = 'yoursmtppassword'; // SMTP password
// Instantiation and passing `true` enables exceptions
// La instanciación y el paso de `true` habilita excepciones
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = $smtp_host;
$mail->Username = $smtp_username;
$mail->Password = $smtp_password;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = $smtp_port;
$mail->CharSet = "UTF-8";
$mail->setFrom($smtp_username, $contact_subject);
$mail->addAddress("youremail@example.com"); // Enter the email address you want to send here
$mail->addReplyTo($contact_email, $contact_name);
// Content
$mail->isHTML(true);
$mail->Subject = $contact_subject;
$mail->Body = $mail_content;
$mail->AltBody = strip_tags($mail_content);
$mail->send();
$message = true;
echo $message;
} catch (Exception $e) {
$message = false;
echo $message;
echo "Mailer Error: {$mail->ErrorInfo}";
}
}
}else {
/*
This is if the incoming get parameter doesn't come by js,
this message will greet malicious software developers
*/
echo "<div class='alert alert-danger'>You entered this area without permission.</div>";
}
?>
Gracias por el contact form
Quisiera poner el teléfono como opcional y No obligatorio. Puedes ayudarme?
Gracias!!!
Excelente aporte funciona de lujo, ojala y tuvieras uno para generar reporte de servicios en PDF y enviarlo al cliente saludos desde México
Revisando como que hay un lag de tiempo en validar los datos en navegador chrome; en opera y edge me ha funcionado sin problemas