Feedback form in jQuery and PHP. Feedback form script

When launching a new web project, there is nothing more pleasant than immediately receiving positive reviews and gratitude from the first visitors. Unfortunately, the owners of many websites overlook this fact, and it is quite difficult to contact the administration on their site.

Today we will tell you about a simple solution to the problem. This form, using jQuery, PHP and PHPMailer, will allow you to receive feedback from visitors directly to your email.

HTML

Let's start with HTML markup. The style sheet is included at the beginning of the document, and the javascript sources are included at the end. This improves performance speed since the scripts are loaded last while the rest of the website is already loaded and rendered.

: feedback.html


Quick Feedback Form w/ PHP and jQuery | Tutorialzine Demo


In the body of the document we see the DIV “#feedback”. Its fixed positioning is confined to the lower right corner of the window, which you can see in the next section of the article.

Inside it there are 5 colored spans (span). Their width is 20% of the document, and they are aligned to the left. This way they will fill the entire width of the #feedback DIV.

Finally, in the container.section, which contains the title and header, there is a button and a text input field.


CSS

Moving on to editing form styles, we first need to say something about how the style sheet is structured. As you can see from the CSS definitions below, each rule begins with #feedback. This way we achieve the CSS equivalent of namespaces, which makes it easier to add code to an existing site and helps avoid possible conflicts.

: styles.css – Part 1

#feedback(
background-color:#9db09f;
width:310px;
height:330px;
position:fixed;
bottom:0;
right:120px;
margin-bottom:-270px;
z-index:10000;
}

#feedback.section(
background:url("img/bg.png") repeat-x top left;
border:1px solid #808f81;
border-bottom:none;
padding:10px 25px 25px;
}

#feedback .color(
float:left;
height:4px;
width:20%;
overflow:hidden;
}

#feedback .color-1( background-color:#d3b112;)
#feedback .color-2( background-color:#12b6d3;)
#feedback .color-3( background-color:#8fd317;)
#feedback .color-4( background-color:#ca57df;)
#feedback .color-5( background-color:#8ecbe7;)

#feedback h6(
background:url("img/feedback.png") no-repeat;
height:38px;
margin:5px 0 12px;
text-indent:-99999px;
cursor:pointer;
}

#feedbacktextarea(
background-color:#fff;
border:none;
color:#666666;
font:13px "Lucida Sans",Arial,sans-serif;
height:100px;
padding:10px;
width:236px;

Moz-box-shadow:4px 4px 0 #8a9b8c;
-webkit-box-shadow:4px 4px 0 #8a9b8c;
box-shadow:4px 4px 0 #8a9b8c;
}
The first element we need to format is the #feedback DIV. He was given fixed positioning, and it is confined to the browser window. Next comes the definition of DIV.section and five colored spans. These spans differ only in the background color specified by the different classes.

At the very end we have CSS rules that define appearance text input fields.

: styles.css – Part 2

#feedback a.submit(
background:url("img/submit.png") no-repeat;
border:none;
display:block;
height:34px;
margin:20px auto 0;
text-decoration:none;
text-indent:-99999px;
width:91px;
}

#feedback a.submit:hover(
background-position:left bottom;
}

#feedback a.submit.working(
background-position:top right !important;
cursor:default;
}

#feedback.message(
font-family:Corbel,Arial,sans-serif;
color:#5a665b;
text-shadow:1px 1px 0 #b3c2b5;
margin-bottom:20px;
}

#feedback .arrow(
background:url("img/arrows.png") no-repeat;
float:right;
width:23px;
height:18px;
position:relative;
top:10px;
}

#feedback .arrow.down( background-position:left top;)
#feedback h6:hover .down( background-position:left bottom;)
#feedback .arrow.up( background-position:right top;)
#feedback h6:hover .up( background-position:right bottom;)

#feedback.response(
font-size:21px;
margin-top:70px;
text-align:center;
text-shadow:2px 2px 0 #889889;
color:#FCFCFC;
}
In the second part of the style sheet, you can see the definition of the confirm (submit) button. Please note that the button has three positions that are tied to the same background image– submit.png, and it is displayed only when needed. Provisions: standard position, mouseover position, and active position"working". When the button is in the working position, the mouseover effect is disabled.


jQuery

At the form feedback There are two positions: hidden and revealed. When it is loaded, its standard position is set to hidden. But when the user clicks on the title, it expands using jQuery. This is implemented through event monitoring and triggering simplest animation, as you can visually see below.

: script.js – Part 1

$(document).ready(function())(

// The relative URL of the submit.php script.
// You will probably have to change it.
var submitURL = "submit.php";

// Caching the feedback object:
var feedback = $("#feedback");

$("#feedback h6").click(function())(

// We are storing the values ​​of the animated
// properties in a separate object:

Var el = $(this).find(".arrow");

If(el.hasClass("down"))(
anim = (
mb: -270,
pt: 10
};
}

// The first animation moves the form up or down, and the second one
// moves the "Feedback" heading, so it fits in the minimized version

Feedback.stop().animate((marginBottom: anim.mb));

Feedback.find(".section").stop().animate((paddingTop:anim.pt),function())(
el.toggleClass("down up");
});
});
To keep our code neat, we moved the if statements to the top of the document, and created an anim object that holds the animation values. Depending on whether there is a "down" class on the arrow, we hide or reveal the form.

The second part of script.js contains the structure of AJAX interaction with submit.php.

: script.js – Part 2

$("#feedback a.submit").live("click",function())(
var button = $(this);
var textarea = feedback.find("textarea");

// We use the working class not only for styling the submit button,
// but also as kind of a "lock" to prevent multiple submissions.

If(button.hasClass("working") || textarea.val().length return false;
}

// Locking the form and changing the button style:
button.addClass("working");

$.ajax((
url: submitURL,
type: "post",
data: ( message: textarea.val()),
complete: function(xhr)(

Var text = xhr.responseText;

// This will help users troubleshoot their form:
if(xhr.status == 404)(
text = "Your path to submit.php is incorrect.";
}

// Hiding the button and the textarea, after which
// we are showing the received response from submit.php

Button.fadeOut();

Textarea.fadeOut(function())(
var span = $("",(
className: "response",
html:text
})
.hide()
.appendTo(feedback.find(".section"))
.show();
)).val("");
}
});

Return false;
});
});
Here we are using AJAX method lower level jQuery - $.ajax(), through which interaction with submit.php is implemented. This method gives us a little more control over the connection than $.get() or $.post().

One big advantage this method lies in "full" return message. Here we define a match between the response and the 404 error, which politely tells the user to check the submitURL path.

Now let's continue and move on to the final part of the tutorial - the PHP section

PHP

PHP contains the information passed through AJAX, processes it, and sends a message to your email inbox.

: submit.php

// Enter your email address below
$emailAddress = " [email protected]";

// Using session to prevent flooding:

session_name("quickFeedback");
session_start();

// If the last form submit was less than 10 seconds ago,
// or the user has already sent 10 messages in the last hour

if($_SESSION["lastSubmit"] && (time() - $_SESSION["lastSubmit"] 10))(
die("Please wait for a few minutes before sending again.");
}

$_SESSION["lastSubmit"] = time();
$_SESSION["submitsLastHour"]++;

require "phpmailer/class.phpmailer.php";

if(ini_get("magic_quotes_gpc"))(
// If magic quotes are enabled, strip them
$_POST["message"] = stripslashes($_POST["message"]);
}

if(mb_strlen($_POST["message"],"utf-8") die("Your feedback body is too short.");
}

$msg = nl2br(strip_tags($_POST["message"]));

// Using the PHPMailer class

$mail = new PHPMailer();
$mail->IsMail();

// Adding the receiving email address
$mail->AddAddress($emailAddress);

$mail->Subject = "New Quick Feedback Form Submission";
$mail->MsgHTML($msg);

$mail->AddReplyTo("noreply@".$_SERVER["HTTP_HOST"], "Quick Feedback Form");
$mail->SetFrom("noreply@".$_SERVER["HTTP_HOST"], "Quick Feedback Form");

echo " Thank you!";
To begin with, we will use the control PHP sessions to calculate how many times a user has used a form in the past hour. If the user tries to send a message less than 10 seconds after it was sent last message or sends more than 10 messages within an hour, an error will be displayed to him.

Messages are sent using the PHPMailer class. It only works with PHP5, so the server needs to support this version.

A number of PHPMailer methods are used to configure outgoing messages. With IsMail() we tell the class to use the internal PHP mail() function. AddAddress() adds recipients (you can add more than one recipient there). After adding the object to the body of the document, we specify the response address and send the message.

This concludes our development!

In conclusion

You can use this form to collect feedback from visitors. With this form, you make it much easier for users to write reviews, and many users simply won’t write a review if it requires clicking somewhere else and going somewhere else. You can also easily design the form at your own discretion or according to a website template.

In accordance with the Federal Law of July 27, 2006 No. 152-FZ “On Personal Data”, I, the subject of personal data, hereinafter referred to as the User, submit information through feedback forms (hereinafter referred to as Forms) on the website (hereinafter referred to as the Site ), as well as to the corporate email addresses of the Law Office "Business Fairway" ending in (hereinafter referred to as Corporate Mail), I freely, in my own free will and in my interest, express to the Law Office "Business Fairway" (OGRN 1167700058679; INN 9705068808), located at the address: 109240, Moscow, Goncharnaya street, building 24, (hereinafter referred to as the Operator), consent to the processing of my personal data (hereinafter referred to as the Consent) on the following conditions.

1. The moment of acceptance of Consent is marking the corresponding field in the Form and clicking on the submit button of the Form on any page of the Site, as well as clicking on the submit button email, containing the User’s personal data, to the address Corporate mail Operator.

2. Processing of personal data – any action (operation) or set of actions (operations) performed using automation tools or without the use of such means with personal data, including collection, recording, systematization, accumulation, storage, clarification (updating, changing), extraction, use, transfer (distribution, provision, access), depersonalization, blocking, deletion, destruction of personal data.

3. Processing of personal data is carried out both with the use of automation tools, including in information and telecommunication networks, and without the use of such tools.

4. Consent is given to the processing of the following personal data of the User specified by the User in the Forms, in files attached to the Forms, as well as information sent to Corporate mail addresses:

    Full Name;

    E-mail address;

    contact number;

    Age;

    Other personal data specified by the User in the Forms or files attached to the Forms.

5. Purposes of processing personal data:

    User identification;

    Interaction with the User, including sending notifications, requests and information regarding the Operator’s services, as well as processing requests and applications from the User and establishing feedback from the User to the Operator;

    Answers to User requests;

    Ensuring the User’s work with the Operator’s Website;

    Sending analytical materials to Users and informing Users about upcoming events organized by the Operator, as well as registration of Users to participate in such events;

    Conclusion of agreements with the User, including employment and service agreements legal services;

    Direction of information and other information to Users marketing information, by sending messages to the email address specified by the User.

    Providing Users with advice on issues related to the services provided by the Operator, for the purposes of marketing activities and support for Users, as well as for other purposes that do not contradict current legislation Russian Federation and the terms of agreements between the Operator and Users.

6. During the processing of personal data, the Operator has the right to collect, record, systematize, accumulate, store, clarify (update, change), extract, use, transfer (distribution, provision, access), depersonalize, block, delete, destroy the User’s personal data .

7. The operator takes necessary and sufficient organizational and technical measures to protect personal information Users from unauthorized or accidental access, destruction, modification, blocking, copying, distribution, as well as from other misconduct third parties.

8. The transfer of the User’s personal data to third parties is not carried out, with the exception of the successors of the Operator during its reorganization and persons processing personal data on behalf of the Operator and on his behalf. If Users participate in events organized by the Operator, the latter has the right to disclose the relevant personal data of Users to persons participating in the organization of such an event.

9. Consent to the processing of personal data is issued by the User for the period necessary for the Operator to achieve the purposes of processing personal data.

10. Consent may be revoked by the User by sending a written statement to the Operator (109240, Moscow, Goncharnaya Street, 24) or by sending a written statement to the following Corporate email address: .

11. This Consent is valid all the time until the termination of the processing of personal data.

12. The concepts used in this Agreement must be interpreted in accordance with their definitions given in Federal law dated July 27, 2006 N 152-FZ “On Personal Data”.

The information presented on this page is aimed primarily at beginner webmasters.

Hello, friends, dear visitors of my humble site! Surely, many of you, including novice webmasters, know what FOS (feedback form) is and why it is needed.

Traditional FOS in its own right simple version– this is when the user fills out the fields of a form located on a web page, and server program processes this data and sends it to Mailbox site administrator. But, there are other options and we will look at one of them in this lesson.

It is clear that when using CMS, for example free Joomla and WordPress, the issue of feedback can be solved using various extensions or plugins, but there are alternative ways, which can be useful for any project built on both pure HTML, PHP, and using the engine.

On the Internet you can find quite a lot of scripts for various FOS - both simple and very sophisticated, which are installed on the site as a full-fledged CMS and require not only PHP support, but also a database for their work. You will most likely have to search, find and try out many options that are right for you.

Feedback is also possible through a comment form open to everyone, where visitors communicate with the site administration and among themselves, solving questions and problems, while FOS involves more closed, secluded communication between two people. Visitors and clients always have questions, so to speak, not for public viewing and publicity.

It’s also worth saying that there are good services for creating feedback forms, but now we’ll talk about one interesting and unconventional FOS. Its main difference from other samples is that it does not require the presence and use mail client. This is a web form and messages in it are created, sent on a web page and received on a web page. In other words, this form works within your site's server, without using any email server.

On free hosting The SMTP server is not available with PHP, so create a service for sending messages from the site page via e-mail to the administrator's email is not possible. The proposed FOS kit solves this problem and provides both the senders of messages from the site page and its administrator with convenient way messaging.

You have the opportunity to check the feedback form in operation, send a message by filling out the fields on the sending page, and also view it on another page with received messages.

A drop of useful information

In the future, in order not to experience difficulties in transcoding files, read this short educational program. To perform conversion, for example, from windows-1251 to utf-8, you need:

  • Open all files in text editor, best in Notepad++;
  • Delete records about old encoding, For example,
    ;
  • Re-encode all files one by one (Encodings → convert to utf-8 without BOM);
  • Insert entries about the new encoding, for example,
    ;
  • Save changes in all files (file → save all).
  • In these actions, it is important to observe the order of operations, otherwise instead of Russian words you will get incomprehensible “crazy words”.

    1. Download required archive with the material and unpack it into current folder on the computer. In the feedback folder you will see an img folder with images and form files. Upload the entire feedback folder to your website server.

    ATTENTION! If files are uploaded to the server, then it is necessary to set the attributes for the message.txt file: 666, otherwise reading and writing to the file will not be possible and the server will display an error message.

    2. Enter the address in the address bar of your browser:
    //your domain/feedback/feedback.php
    The feedback page with the data entry form will load. You can test the form by filling out all fields and sending a message. Make a link to this page from your website in the right place.

    3. To check messages, enter address bar browser address:
    //your domain/feedback/message.php
    The page with the message title, data and text of the sent message will load. To delete all records, click the Delete all button on the page. Bookmark the message page (message.php) so you can easily access it next time.

    FOS is ready to work on your website. How long did it take you to install it?

    Option #2. Installing FOS in a website template.

    This form can also be inserted into a PHP website template. This task is a little more difficult.

    The form will look something like this, and messages can be accepted.


    The files are in utf-8 encoding; if your site is in a different encoding, they need to be re-encoded. You can already do this yourself.

    The pages feedback.php and send.php have preliminary design for clarity, which will not be required in the future due to the fact that the marked required blocks(beginning of block → end of block) in the feedback.php and send.php files will need to be copied and pasted into the page templates of your site. These templates should then be renamed feedback.php and send.php respectively. The Main Menu of your site should contain a link to the feedback page feedback.php.

    The files header.php and footer.php, which are used to generate the feedback.php and send.php pages during preliminary testing, are also not required.

    The message.php and deltext.php files are service pages for the site administrator. They can be left unchanged or decorated to your liking.

    All these files must be in root directory along with the message.txt file:

    To avoid trouble, before uploading files to root folder site, check if the file names match! If there are, the files should be renamed.

    If you are using a site containing regular HTML pages on PHP hosting, then you should insert the form from the feedback.php file into the feedback page template named feedback.html. And into the HTML page template named send.html, insert a script block from the corresponding file and rename the page to send.php.

    This is all! Use FOS to the maximum, communicate with visitors, develop your resource and all the best to you! Don't forget to visit my website. Your L.M.

    Almost every website has a feedback form. And of course there are a lot of different implementations. In this article we will write a feedback form that will use HTML5 validation and pop-up notifications with sound. And of course the request itself will be sent with using ajax. In addition, the example will provide two options for processing the request: via ajax and a regular POST request. In the case of a POST request, flash messages based on the session will be used. More details under the cut...

    So, our project will have the following structure:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 . ├── css │ ├── jquery.jgrowl.css │ ├── main.css │ └── normalize.css ├── images │ └── jgrowl.close.png ├── protected │ ├── bootstrap. php │ ├── flashes.php │ ├── func.php │ └── session.php ├── sounds │ ├── notice.mp3 │ └── notice.ogg ├── feedback.php └ ── index .php

    The index.php file will contain a feedback form. After the user fills out the form and clicks the submit button, an ajax request will be sent to the feedback.php script. Which, in turn, having processed the request, will return the result. There is a nuance here. The script checks which request came and, depending on this, either returns the result in the form of json or writes a flash message to the session and then redirects it back to index.php. That is, in case of any errors in javascript, the request will still be processed by a simple POST request. And in this case, the programmer has a flexible tool that allows him to always abandon ajax.

    Flash messages are a type of session data that is erased after they are first requested. Is very convenient tool to pass messages between requests.

    In order not to complicate the layout, and also to unify notifications for the user, the example uses pop-up growl messages similar to those used in OSX. To do this, use the good jQuery plugin jGrowl, which has a flexible customization and styling system.

    So let's start with the HTML:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 Feedback form Feedback Name: Email: Message: Send //some code

    As you can see from the code above. Not used in the example. It's just not necessary for things like this. All the same, the data will be validated on the server.

    JavaScript:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 $(document) .ready (function () ( buzz.defaults .formats = [ "ogg" , "mp3" ] ; buzz.defaults .preload = true ; if (buzz.isSupported () ) ( var noticeSound = new buzz. sound ("sounds/notice" ) ; ) $.jGrowl .defaults .position = "top-right" ; $.jGrowl .defaults .closer = false ; $.jGrowl .defaults .beforeOpen = function (e, m, o) ( if (noticeSound) noticeSound.play () ; ) ; $("form#feedback-form" ) .on ("submit" , function (e) ( e.preventDefault () ; $(this ) .ajaxSubmit (( dataType : "json" , success: function (response) ( $.jGrowl (response.message, ( theme: response.type ) ) ; if (response.type == "success" ) $("form#feedback-form" ) [ 0 ] .reset () ; , error: function () ( $("form#feedback-form" ) .unbind ("submit" ) .submit () ; ) ) ) ) ;

    The code above is very clear. Setting up notifications and sound playback. And also the implementation of the form operation without reloading the page using the ajaxForm library.

    Now let's move on to implementing request processing:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 //feedback.php require __DIR__ . "/protected/bootstrap.php" ; if (! IS_POST() ) ( stopAndResponseMessage( "error" , "The script only accepts POST requests!" ) ; ) $name = _POST("name" ) ;

    $email = _POST("email" , false ) ; $message = _POST("message" ) ; if (! $name || ! $email || ! $message ) ( stopAndResponseMessage( "error" , "Not all required fields were filled in!" ) ; ) // check captcha and csrf token if (! isEmail($email ) ) ( stopAndResponseMessage( "error" , "Email address is bad!" ) ; ) if (mb_strlen ($message ) _e( $type ) , "message" => _e($message ) ) ; exit ; ) Flashes:: add (_e($type ) , _e($message ) ) ; The most important place in the script this is the stopAndResponseMessage function, which is a flexible request processing mechanism. It returns a json response in case ajax request or uses flash messages when idle POST request