How to send a mail with php ajax and jquery in facebook style
One of the website that I love is facebook. I’m not talking about the social network, well I like this social network, but I prefer twitter and linkedin for “professional use”, but this is another question, because I’m talking about the design.:)
The use of web 2.0 effects and Ajax make this web site on of my favourites.
With this tutorial I will explain you how to create a message mail system like Facebook.
For make this we need to create some files.
1. The index file with the mail form.
2.The mail.php file that process the form and send the mail, using the simple function mail() of php.
3.A css file .
4.Jquery, naturally.
5.An other Javascript, called Ajax.js, to interact with ajax, php and jquery.
Surely you can put all in one file, but, for a better understanding and to have a clean code, I prefer to use different files for each one.
Well first of all you can see a demo of this page here, for logical reason I’ve deleted my mail from the source code, / you can use your mail to test the script) this is the only thing that you need to change before use the source code, the rest is ready for use.
OK, start with this tutorial. First we need to create the form page and link to this page the jquery and ajax,js script, so this is the code :
<div>
<div id=”response”></div>
<form id=”formail” action=”" method =”post”>
<label>Name : </label>
<input type=”text” name=”name” id=”name” />
<label>Your mail :</label>
<input type=”text” name=”mail” id=”mail” />
<label>Subject : </label>
<input type=”text” name=”subject” id=”subject” />
<label>Text :</label>
<textarea name=”text” id=”text” cols=”40″ rows=”10″></textarea>
<input type=”submit” value=”send mail” id=”sendmail” name=”sendmail” />
</form>
</div></div>
The div called response, will be util for the validation and the text message after send the mail( or to get the error if the mail script doesn’t work), this div is really important don’t forget this.
Now we need to style this, you can style the form as you want, but the only important thing is that the div response must be in display none :
#response{display:none;}
Is better if you style this and the form, it will look more pretty this is the complete css that I’ve used :
body{
background: #E7E7DC;
font-size: 13px;
font-family: arial;
}
#wrap{
width: 800px;
background: white;
margin: auto;
padding: 10px;
}
#wrap h1{
padding: 10px;
border: 1px solid #ccc;
background: #f8f8f8;
}
.mail{
width:500px;
margin:auto;
}
#formail{
width: 500px;
margin: auto;
}
#formail label{
display: block;
margin: 10px 0;
}
#text{
background: #f8f8f8;
}
#sendmail{
margin-top: 20px;
display: block;
}
#response{
display: none;
border: 1px solid #ccc;
background: #FFFFA0;
padding: 10px;
width: 450px;
}
This is the style of the page, now it comes the nice part, the php and the ajax, this will be funny! Let’s go and create the mail.php page, with this code :
<?php
$mail = $_POST['mail'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$text = $_POST['text'];$to = “yourmail@domain.com”;
$message =” You received a mail from “.$mail;
$message .=” Text of the message : “.$text;if(mail($to, $subject,$message)){
echo “mail successful send”;
}
else{
echo “there’s some errors to send the mail, verify your server options”;
}
?>
Ok, let me explain this:
Firs I create the variables that will contain the froms data values :
$mail = $_POST['mail'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$text = $_POST['text'];
With the variable $to, I store the mail where I want that the mail will be sended( my mail), this is the only thing that you must change to make works the script.
The $message variable get the mail and the text of the sender, and put in the body of the mail message.
Finally , with tha mail() function from php I send the mail. I’ve used an if because, if the mail doesn’t work you will know.
The mail function is really simple and accept some parameters, the mail where send, the subject and the message of the mail.
You can read all from the official page of php.
Now is the time of the ajax.js. This is the complete code :
$(document).ready(function(){
$(“#sendmail”).click(function(){
var valid = ”;
var isr = ‘ is required.’;
var name = $(“#name”).val();
var mail = $(“#mail”).val();
var subject = $(“#subject”).val();
var text = $(“#text”).val();
if (name.length<1) {
valid += ‘<br />Name’+isr;
}
if (!mail.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += ‘<br />A valid Email’+isr;
}
if (subject.length<1) {
valid += ‘<br />Subject’+isr;
}
if (text.length<1) {
valid += ‘<br />Text’+isr;
}
if (valid!=”) {
$(“#response”).fadeIn(“slow”);
$(“#response”).html(“Error:”+valid);
}
else {
var datastr =’name=’ + name + ‘&mail=’ + mail + ‘&subject=’ + subject + ‘&text=’ + text;
$(“#response”).css(“display”, “block”);
$(“#response”).html(“Sending message …. “);
$(“#response”).fadeIn(“slow”);
setTimeout(“send(‘”+datastr+”‘)”,2000);
}
return false;
});
});
function send(datastr){
$.ajax({
type: “POST”,
url: “mail.php”,
data: datastr,
cache: false,
success: function(html){
$(“#response”).fadeIn(“slow”);
$(“#response”).html(html);
setTimeout(‘$(“#response”).fadeOut(“slow”)’,2000);
}
});
}
What i’ve done? let me explain :
I suppose that you know the $(document).ready function of jquery, I’ve explained in the previous tutorial, create an animated menu with jquery.
When #sendmail, the submit button of the form, is clicked will start the validation of the form, this is important try always to validate your forms, expecially for the breakballs(usually called spammer…), so the first part of the script validate the form and if on of the input value is under 0 this will stop the script and return an error like in this image
the text that appears is stored in the #response div, for this reason I said that is important and not only for this.
var valid = ”;
var isr = ‘ is required.’;
var name = $(“#name”).val();
var mail = $(“#mail”).val();
var subject = $(“#subject”).val();
var text = $(“#text”).val();
if (name.length<1) {
valid += ‘<br />Name’+isr;
}
if (!mail.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += ‘<br />A valid Email’+isr;
}
if (subject.length<1) {
valid += ‘<br />Subject’+isr;
}
if (text.length<1) {
valid += ‘<br />Text’+isr;
}
To validate the mail, I’ve used a regular expression( thanks to Juan Carlos
)
if (!mail.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i))
if you try to write 2 mail addres, this will not works, or if you use white space in the mail field the validation will stop the script. You can try simply leaving white the various fields to understand how it works. All of the error in the validation will appears in the response div, that will appear with a fadeIn effect.
if (valid!=”) {
$(“#response”).fadeIn(“slow”);
$(“#response”).html(“Error:”+valid);
}
The second part of the script is for create the datastr variable, that will store the value from the form and send in the ajax request, and make appear again the #response div, yes how I said is important ejejeje, like the facebook style, that say that the message is sending.
else {
var datastr =’name=’ + name + ‘&mail=’ + mail + ‘&subject=’ + subject + ‘&text=’ + text;
$(“#response”).css(“display”, “block”);
$(“#response”).html(“Sending message …. “);
$(“#response”).fadeIn(“slow”);
setTimeout(“send(‘”+datastr+”‘)”,2000);
}
In the final part I’ve used a “return false“, so when you click on the submit button this doesn’t do nothing, well it seems that the button doesn’t do nothing, but the reason ts that the rest of the work is done by ajax and the function send :
function send(datastr){
$.ajax({
type: “POST”,
url: “mail.php”,
data: datastr,
cache: false,
success: function(html){
$(“#response”).fadeIn(“slow”);
$(“#response”).html(html);
setTimeout(‘$(“#response”).fadeOut(“slow”)’,4000);
}
});
}
This is the “core” of the script, this will call the $.ajax function of Jquery, give it the parameters and call the mail.php file, finally get the response of the mail.php, and return this in the response div, and after 4 seconds the text fade out.
This script is inspired ,how I said, from facebook message system and it works at the same way, you can use on your own and change or modify the source code.
Download directly the script.
I hope is useful , you can use the comments and let me know what do you thing.
If you know something to improve the script, let me know pls.
Bye !!
84 appreciated comments. + Add your
« Older CommentsTrackbacks/Pingbacks
-
[...] How To Send A Mail With PHP, Ajax And jQuery [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]
-
[...] [...]
-
hi guys…
hi guysI would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well and i have start my own blog now, , thanks for your effort…
-
[...] First of all, here is a great tutorial: How to send email with php ajax and jquery [...]
-
[...] How to send a mail with php ajax and jquery [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]
-
[...] How to Send Facebook-Style Mail with PHP, AJAX and jQuery The Facebook website is choc full of unique features, especially the system for sending mail and messages. Using PHP, AJAX and jQuery, you can recreate this technique using this step-by-step tutorial. View the demo. [...]

Thanx for this great script. This helped me a lot. But I have a question concerning sending multiple mail. For instance one to the receiver and one back to the sender of the message. I tried this code: mail($mail, $subject_absender,$message_absender,$to);
if(mail($to, $subject,$message,$header)){
echo “mail successful send”;
}
else{
echo “there’s some errors to send the mail, verify your server options”;
}
or
if(mail($to, $subject,$message,$header) && mail($mail, $subject_absender,$message_absender,$to)){
echo “mail successful send”;
}
else{
echo “there’s some errors to send the mail, verify your server options”;
}
or this
if(mail($to, $subject,$message,$header)){
mail($mail, $subject_absender,$message_absender,$to)
echo “mail successful send”;
}
else{
echo “there’s some errors to send the mail, verify your server options”;
}
Can somebody give me a hint, how I can solve this problem?
Greetings
dangorges
What a great function!
I’m trying to use it in conjunction with the jQuery validate plugin. But I seem to have issues with it.
Below is the script I have on my page..
Any advice would be greatly welcomed.
Thanks,
Jonathan
jQuery(function($) {
$(“#sendmail_form”).validate();
$(“#sendmail”).click(function(){
var NameFrom = $(“#NameFrom”);
var EmailFrom = $(“#EmailFrom”);
var NameTo = $(“#NameTo”);
var EmailTo = $(“#EmailTo”);
var Subject = $(“#Subject”);
var MessageOptional = $(“#MessageOptional”);
var datastr =’NameFrom=’ + NameFrom + ’&EmailFrom=’ + EmailFrom + ‘&NameTo=’ + NameTo + ‘&EmailTo=’ + EmailTo + ‘&Subject=’ + Subject + ‘&MessageOptional=’ + MessageOptional;
$(“#response”).css(“display”, “block”);
$(“#response”).html(“Sending message… “);
$(“#response”).fadeIn(“slow”);
setTimeout(“send(‘”+datastr+”‘)”,2000);
return false;
});
function send(datastr){
$.ajax({
type: “POST”,
url: “mail.php”,
data: datastr,
cache: false,
success: function(html){
$(“#response”).fadeIn(“slow”);
$(“#response”).html(html);
setTimeout(‘$(“#response”).fadeOut(“slow”)’,4000);
}
});
}
});
Ciao! grazie e
bellissimo script. ma cè un problema che vedo nessuno ha segnalato.
Se nel messaggio text si scrive un a capo( schiacciando enter) il messaggio non viene inviato, e il caricamento di invio messaggio si blocca all’infinito…
Come risolvere?
Ciao! thank u for the amazing script. but there is a problem.
If i press “enter” key in the message text ,the mail will not submit, and the loader of the mail submit get stuck…
How can be resolved?
did you find a solution for this? i face the same issue. please help.
Hi, your form is very cool, but I have one problem during applying it into my site. When I don’t fill any values into form, the validation doesn’t work and submit button makes nothing. If I type anything into form inputs, the error messeges appears. Could you help me?
Hi guys!
first of all, thanks for all your comments. I’m sorry but in the last months I’ve been really busy with my new relocation, this is why usasully I do not respond to the comment, again sorry for that.
I will try, further to respond to all, anyway in the previous comments, you can find some solution applied to this script.
As I said it before the purpose of this script is to teach how to use some techniques so better to use it for learning than create your own script and use it.
Anyway leave your question here, I will try to respond when it will be possible for me, I said I’m relocating in a new country and have no time now to dedicate to my blog, again, sorry for that.
Cheers!
Hey, cool script. But your php code does not seem to be submitting the “Name” field at all.
I made some changes in mail.php file – this will make resived e-mail look more “proper”
I changed $message to : $message =”From: $name\n E-Mail: $mail\n Message:\n $text”;
Hi everyone,
I’m trying to send a checkbox array with the mail script, but every time I do it comes back as undefined. How should the array be treated in the ajax file?
Currently when defining it in , I have:
var checkboxExample = $(“#checkboxExample”).val();
It is then added to the datastream as:
… ‘&checkboxExample=’ + checkboxExample;
Any tips would be amazingly helpful.
Cheers,
Ed
I would say, just perfect tutorial and nicely explain..
thanks
Nice tutorial. This saved me a lot of time
Great tutorial! Thanks!
I had problem with this string of code:
setTimeout(“send(‘”+datastr+”‘)”,2000);
This doesn’t work so I found a solution to the problem.
setTimeout(function(){
send(datastr);
}, 2000);
You have to do it like this if you want to pass a parameter to the function within setTimeout().
Thanks for a great tutorial nonetheless