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
Newer Comments »Trackbacks/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. [...]

a little complicated, but worth of trying
vey nice. I am trying to incorporate into a wordpress footer. Unfortunatly, the path to “mail.php” changes from page to page. Is there a way to referance mail.php in a dynamic way threw js?
thanks peter
solution:
this before the js includes
<script type=\\"text/javascript\\"><!–
var mail_url = \\"<?php bloginfo(\\\’template_url\\\’); ?>/mail.php\\";
// –>
</script>
then change url: mail_url in the send function
Hi Peter, yes you can use the bloginfo tag from wordpress :
http://codex.wordpress.org/Template_Tags/bloginfo
Nice, but demo doesn\’t work. 404 error
HI Ivan, sorry I changed the server and forgot to upload again the test folder, now it works.
Thanks for remind me!
Hello!!!! I just want to say Thankyou for the email form i was tryng a lot another methods but this one is perfect for me
take a look in my site and send me a message 
Thanks once again!
This is a great script, could anyone help explain how I could modify it slightly to display a ‘Thank You’ page after the form has been submitted?
Many Thanks
This is a great script, could anyone help explain how I could modify it slightly to display a \’Thank You\’ page after the form has been submitted?
Many Thanks
Very useful solution but, when I try tu put a carriage return in the textarea, stop working…
I’ve been reading info on your site for quite some time now, never really got a chance to post anything. Just want to say you always have the best information and thank you for that
Interesting this is hard to find. Thanks for a good article.
Thanks for all the helpful article. They really helped me a lot! Between, you just got a new subscriber now!
I’m glad to see you posting, and will keep reading if you continue publishing.
Great post, I
Hi,
I’m testing this out and it seems to stop with a response “sending message”…
what am I doing wrong?
Thanks.
Awesome script. Thank you. Carriage returns in the message box definitely stops the script. Perhaps add your fix (encodeURIComponent(text);) to the downloaded files?
Try putting:
var datastr =’name=’ + name + ‘&mail=’ + mail + ‘&subject=’ + subject + ‘&text=’ + encodeURIComponent(text);
in the ajax.js file.
The “encodeURIComponent()” function encodes the carriage return character in the textarea.
It works for me.
Great Thanks
Try putting:
var datastr =’name=’ + name + ‘&mail=’ + mail + ‘&subject=’ + subject + ‘&text=’ + encodeURIComponent(text);
in the ajax.js file.
The \"encodeURIComponent()\" function encodes the carriage return character in the textarea.
It works for me.
THANKS A BUNCH !!
That surely did the trick.
another question… how can I swap the sender’s email with the default “CGI-Mailer” when I receive the email?
thanks
another question… how can I swap the sender\’s email with the default \"CGI-Mailer\" when I receive the email?
thanks
Hi
I have also been testing this form and so far so good but in Safari it seems to just hang at the ‘sending message…’ stage.
Does anyone know if the solution posted above by visualKom would fix this issue too? If, so where would I place that piece of code?
Sorry for all the questions, quite new at this.
@jazzybuzz: look here > http://php.net/manual/en/function.mail.php
@ss: replace the row just after “else” in the ajax.js file. It works for me on Safari, FF, IE and Chrome, in Mac OS X, Linux and Windows platforms.
does anyone know how to reset the fieldbox values after submit? I’ve tried everything I could find on this matter and nothing is working correctly.
thanks.
Hi, I came across this article while searching for help with JavaScript. I have recently switched browsers from Opera to Internet Explorer 7. After the change I seem to have a problem with loading JavaScript. Every time I go on a website that needs Javascript, the site doesn’t load and I get a “runtime error javascript.JSException: Unknown name”. I cannot seem to find out how to fix the problem. Any aid is very appreciated! Thanks
to visualKom:
Nothing happens for me, I try to put this line, but still ‘sending message…’. Any ideas?
to visualKom:
Nothing happens for me, I try to put this line, but still \’sending message…\’. Any ideas?
I would like to thanku for this good artical it’s very helpfull for anyone..
but can u wirte a tuturial about how to creat a ( leave a Replay) like the one i’m using now to leave u this message..
it will be great if u can help..
many thanx..
I would like to thanku for this good artical it\’s very helpfull for anyone..
but can u wirte a tuturial about how to creat a ( leave a Replay) like the one i\’m using now to leave u this message..
it will be great if u can help..
many thanx..
I’ve been using this form but it seems I can’t have a space in the name field and now all of a sudden it has just stopped sending the mail. I don’t understand why, the script hasn’t been touched in over a month.
Any help guys?
Thanks
I was getting a problem with the mail script hanging because of apostrophes and what-not. So I pulled the function out and into the setTimeout like so:
setTimeout( function() {
$.ajax({
type: “POST”,
url: “mail.php”,
data: datastr,
cache: false,
success: function(html){
$(“#response”).fadeIn(“slow”);
$(“#response”).html(html);
}
});
}, 2000 );
Hope this clear enough to help.
I was getting a problem with the mail script hanging because of apostrophes and what-not. So I pulled the function out and into the setTimeout like so:
setTimeout( function() {
$.ajax({
type: \"POST\",
url: \"mail.php\",
data: datastr,
cache: false,
success: function(html){
$(\"#response\").fadeIn(\"slow\");
$(\"#response\").html(html);
}
});
}, 2000 );
Hope this clear enough to help.
Does this form work on facebook page? I was trying to get these codes on facebook page and seems doesnt work, nothing happen. This is what I have done, please point my mistake. Appreciate it.
I have created the following files.
1. fb.css – contain the style code as above (copy & paste)
2. mail.php – copy & paste the above mail code.
The above files – fb.css and mail.php are placed on my domain server.
On facebook FBML tab, I have copied the email form code (as above) and followed by the ajax code with tags before and after ajax code.
I have added the following before my email form code;
and edited the code for ajax code.
url: “http://www.mydomain.com/fb/mail.php”
What have i done wrong? Any help, please?
Does this form work on facebook page? I was trying to get these codes on facebook page and seems doesnt work, nothing happen. This is what I have done, please point out my mistake. Appreciate any help.
I have created the following files.
1. fb.css – contain the style code as above (copy & pasted as above)
2. mail.php – copy & paste the above mail code.
The above files – fb.css and mail.php are placed on my domain server.
On facebook FBML tab, I have copied the email form code (as above) and followed by the ajax code with “”, “” tags before and after ajax code.
I have added the following before my email form code;
<link href=”http://www.mydomain.com/fb/fb.css” rel=”stylesheet” type=”text/css” />
and edited the code for ajax code.
url: “http://www.mydomain.com/fb/mail.php”
What have i done wrong? Any help, please?
Great tutorial but it has a huge flaw.
If you insert a break line in the textarea the form will not submit!
For example if you write
“Hello
Bye”
Then the from doesn’t submit.
Do you have a solution for this?
Thx!
Hi,
Can this sample code be used on facebook page? I have tried but doesnt work. Can anyone be able to help to get it work on facebook page? Appreciate any helps.
Thanks!
It seems there is something wrong in your code.=( I get some error\’s in my mail form.=(
hopefully this comment doesn’t appear multiple times (it seems to freeze once i try to post my comment.. not sure if it’s actually posting), but all I really wanted to say was helpful tutorial for me.
En yeni ask siirleri! videolari ask siirleri.
I found your blog on google and read a few of your other posts. I just added you to my Google News Reader. Keep up the good work Look forward to reading more from you in the future.
thanks ill try using this code
Thanks for this code, it’s really useful.
Thanks for your post. I like the design, but I would like to add some span security. Almost any captcha code will work, but Ive tried for hours, and something keeps creating errors in weird locations. Im not new to PHP, and we’ve all had those instances where we try everything for hours only to find a comma or space created the error, so I decided to go straight to the source and save some time. What do you recommend and can you post the code please? Thanks
Great article and elegant way of handling messages … however there were some issues …
The style for the response div showed as off yellow for the background and white for the text. It was not possible to see the text, so I just changed the background and text color to suit.
I also moved the div within the form because the response div was appearing outside my form, centered on screen instead of within my form. I put it under the submit button so it would be seen when the user tried sending.
I also added a line to change the color of the result message where fields were missing.
In the text of the article there is a missing parentheses. Since I’m not yet used to php syntax, it took me a good hour to figure out what the problem was. Here is the code I used ….
function send(datastr) {
$.ajax(
{
type: “POST”,
url: “php/sendMail.php”,
data: datastr,
cache: false,
success: function(html)
{
$(‘#response’).css(‘color’, ‘white’);
$(‘#response’).fadeIn(‘slow’);
$(‘#response’).html(html);
setTimeout(‘$(“#response”).fadeOut(“slow”)’,2000);
}
}); // This parentheses was missing.
};
Great tutorial but it has a huge flaw.
If you insert a break line in the textarea the form will not submit!
For example if you write
“Hello
Bye”
Then the from doesn’t submit.
Do you have a solution for this?
Thx!
Hello, great and simple tutorial!
If you construct the data string the following way, it will also work with break lines and special characters:
var datastr=$(“#formail”).serialize();
Hi I´m not so in to ajax an jquery. I found the variable in the ajax.js but there are several variables in one form field. How can use several variables with this technique?
If you would help me, this would be great.
dangorges
The style for the response div showed as off yellow for the background and white for the text. It was not possible to see the text, so I just changed the background and text color to suit.
I also moved the div within the form because the response div was appearing outside my form, centered on screen instead of within my form. I put it under the submit button so it would be seen when the user tried sending.
I agree,Great job !
Awesome script. Thank you. I do have one question, however… when text is entered into this message container and a hard return is used, the script won’t send. Do you have a solution or suggestion for this, as I suspect many people use
a hard return (that was a shift+enter) in their comments.
Please help, this is not working for me, I downloaded the code, changed the $to mail recipient to mine, and tested it. The script says the mail was sucsesfully sent but I never receive it in my inbox, what could it be?
Try it online, in your local pc should not work.
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Anyway I’ll be subscribing to your feed and I hope you post again soon.