Plugin for universal form sending to E-mail with site verification

The plugin can be easily integrated into any website without deep analysis of the code and architecture. In this article we will look at the principle of operation of the plugin, the initialization, configuration and installation procedure.

In this article we will offer our experience of universally sending forms to E-mail with checking for completeness using PHP and Jquery. The plugin can be easily integrated into any website without deep analysis of the code and architecture. In this article we will look at the principle of operation of the plugin, the initialization, configuration and installation procedure.

Download the plugin

 Distinctive features and capabilities of the universal form submission plugin:

  • Checking the completeness of forms with the ability to group elements and display hints for the user
  • Many templates for sending with the ability to automatically select a template
  • Form operation without reloading - AJAX
  • Processing successful and failed submissions
  • Unique email headers
  • Sending files by email

A universal plugin for sending forms with email verification consists of the main parts:

  • HTML form to fill out
  • JQuery script for checking and sending AJAX
  • PHP script for automating the processing of data sent from the form, connecting letter templates and processing the result of sending
  • PHPMailer as an smtp client for sending a letter
  • TPL files of email sending templates

Installing an example plugin on the web server host and sending the form to E-mail for the first time

After downloading and unpacking the plugin, we will see the following tree of files and directories:

/css/style.css              // Файл основных стилей
/css/font-awesome.css       // Файл стилей шрифта FontAwesome
/fonts/*                    // Файлы шрифта
/js/script.js               // JQuery скрипт проверки и AJAX отправки формы
/mail-tpl/*                 // Каталог файлов шаблонов
/php/phpmailer/*            // Каталог файлов PHPMailer
/php/config.php             // Конфигурация SMTP подключения
/php/function-send-form.php //Функция обработки и универсальной отправки на почту E-mail
index.html                  // HTML форма отправки

For further first experience of submitting a demo form, we need to configure the /php/config.php file :

$__smtp = array(
"host" => 'smtp.host.ru',
"debug" => 0,
"auth" => true,
"port" => '465',
"username" => 'mail@E-mail.ru',
"password" => '123456',
"addreply" => 'mail@E-mail.ru',
"replyto" => 'mail@E-mail.ru',
"secure" => 'ssl'
);

We will not  dwell in detail on the procedure for configuring the config.php file. More detailed information about PHPMailer SMTP client configuration can be found here!

After successful and correct editing of the configuration file, we need to place the archive files on any web server. This script will not work in the browser mode for viewing local files. Upload all the contents to any folder on the web server host and open the link through the browser address bar:

http(https)://domen.domen/path/to/dir/index.html

If we open a presentation page with a description and a form, everything is done correctly. Next, we fill out the form and wait for the “Submit” button. If the form is submitted successfully, we will display a corresponding message. In case of errors during sending, error information will be displayed. We will not consider the PHPMailer debugging procedure either.

Installation and integration of a plugin for universal form submission by E-mail to the website

To install the plugin on an existing site you need:

1. Copy the following list of files and directories:

/js/script.js               // JQuery скрипт проверки и AJAX отправки формы
/mail-tpl/*                 // Каталог файлов шаблонов
/php/phpmailer/*            // Каталог файлов PHPMailer
/php/config.php             // Конфигурация SMTP подключения
/php/function-send-form.php //Функция обработки и универсальной отправки на почту E-mail

2. Create a new or edit an existing form using the following example:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/script.js"></script>

<form name="request" method="POST" action="php/function-send-form.php" class="sendler">
	<h2>ОБРАТНАЯ СВЯЗЬ</h2>
	<input name="name" title="Введите имя" type="text" placeholder="Имя" class="Y-required" tabindex="1" confirminfo=".response">
	<input name="E-mail" title="Заполните Е-mail" type="text" class="Y-required" placeholder="e-mail" tabindex="2" confirminfo=".response">
	<textarea name="message" title="Заполните сообщение" class="Y-required" placeholder="Сообщение" tabindex="3" confirminfo=".response"></textarea>
	<input type="radio" id="radio1" class="Y-required" name="radio">
	<label for="radio1">radio 1</label>
	<input type="radio" id="radio2" class="Y-required" name="radio">
	<label for="radio2">radio 2</label>
	<input type="radio" id="radio3" class="Y-required" name="radio">
	<label for="radio3">radio 3</label>
	<input type="checkbox" class="checkbox Y-required" title="Необходимо согласие с правилами" id="checkbox" tabindex="4" confirminfo=".response">
	<label for="checkbox">Я ознакомился и согласен с правилами</label>

	<button class="btn btn-contact" type="submit" name="submitbtn" tabindex="5" value="Отправить">Отправить</button>
	<div class="response"></div>
</form>

Description and assignment of key form attributes for the script to work correctly. Optional script parameters are in italics:

2.1. form tag:

name - Defines the name of the tpl template when processing the received POST array by the function-send-form.php script. The name of the letter template must correspond to the value of the name attribute and is formed using the mask " <nameAttr_value>.tpl "

method - the attribute value is always POST. Otherwise, the PHP form processing function will not work. By default, the data processing script function-send-form.php is focused only on POST form parameters.

action - link to the server AJAX request handler. If your AJAX request server handler path is different, you need to edit the attribute value

class - the attribute can contain any number of classes, but for the JQuery script to work correctly, the sendler class must be present. This class tracks the form submission event on your site.

2.2. Fields to be filled out inside the form can contain the following attributes:

name - defines the name of the POST parameter

type - for correct operation of the form and recognition of the types of form elements, the attribute is recommended for mandatory use

title - displays a hint in a tag that is specified by classes in the confirminfo attribute of the current tag

class - all fields that are required to be filled in and checked must contain the class " Y-required ", " group000_Y-required "in the attribute value. group000_Y-required - groups the required elements into groups to check if one of the group elements is full. Radio does not need to be grouped, grouping occurs on the name attribute, as intended by the developers of type

confirminfo - the attribute value determines the tag class where a warning about an empty form element is displayed

2.3. A tag with the response class is defined by default as a class for displaying system messages about the results of form operation, displaying messages in plugin debugging mode, and warnings about incorrectly filled out form elements.

The stylization of this form can be taken from the example, or you can develop your own.

3. As a result of editing or creating a form, JQuery must process the form with the AJAX function. The result of the form should be returned to a tag with the "response" class. If something is not working correctly for you, refer to the example attached as an archive to this article.

The principle of operation of the universal plugin for sending a form to E-mail with verification

The plugin for sending a form to E-mail works in several stages and according to the following principle:

  1. The form submission event with the sendler class is triggered.
  2. The form submission event intercepts the JQuery script and starts the process of checking the form for correct completion.
  3. In case of violations of the form filling rules, the script adds the wrong class to the required fields and, if the necessary title and confirminfo attributes are present, displays messages with hints for filling.
  4. If the form validation is successful, the function of sending the AJAX form is launched with a request to the handler (link) specified in the action attribute.
  5. The server handler receives the necessary parameters of the AJAX request, connects the required letter template (based on the name attribute of the form - POST template parameter). Next, the PHPMailer class is initialized, the body of the letter, headers and the procedure for sending the letter to E-mail are formed.
  6. In case of successful or unsuccessful sending of a letter, the server handler will return the corresponding message to the page in the JQuery script

Rules for creating and editing tpl letter templates

We will not consider the rules for layout of html letters. Let's look at the required tpl parameters of a letter template and the principle of creating templates for a script for universally sending a form to E-mail.

Let's look at an example from the archive:


<?php
// include шапки письма. Удобно использовать для множества шаблонов, где шапка письма остается неизменной
include "header.tpl";
// Тема письма. Параметр необходимы в процедуре отправки письма средствами PHPMailer
$subject = "Форма обратной связи"; 
// Сообщение, которое возвращает серверный обработчик function-send-form.php
$return_msg = "Ваша заявка успешно отправлена!";
 ?>

	<h1>Заказ обратного звонка от: <?php echo $name;?></h1>

	<p style="font-size: 16px;">Данные для обратной связи: <?php echo $email;?></p>

	<p style="font-size: 16px;">Время обратного звонка: <?php $time = date("F j, Y, g:i a"); echo $time;?></p>
				
	<p style="font-size: 16px;">Текст сообщения: <?php echo $message;?></p>

// include футера письма, аналогично шапке
<?php include "footer.tpl"; ?>

As you can replace, the values ​​of the name attributes of the form tags are identical to the names of the variables in the tpl letter template. That's right, that's how it is! We put all newly created templates into the mail-tpl directory with the file extension .tpl

The name of the tpl document must match the value of the name attribute of the submission form on the site.

Completion

Perhaps this is all the necessary information for effective use of the universal plugin for sending forms to E-mail with verification. Thank you all for your attention!