For The Newbies: A simple PHP Contact Form Using Ajax To Send Email

I’ve decided that I will write something for the newbie’s to PHP and show you how to create a simple contact form using AJAX to send an email to your email address.

I remember my first time starting out and learning PHP, damn was it hard to understand the first time. When you practice and write code often you will come to grips with it and as you go along you will get better at it.

So let’s get started with writing code. We are going to write the PHP code that handles the sending of emails first. Yes I know I’m doing it in the reverse order as we are only going to use three fields in our form, the name, email and message field.

The PHP code to handle the form details and sending of the email

// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = '';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From:';

if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message) or die('Error sending Mail'); //This method sends the mail.
echo "Your email was sent!"; // success message

The code above gets the field values posted using the $_POST  variable via the form we will be creating. We then set the variables to hold the TO, SUBJECT, MESSAGE and mail HEADERS information. We also do a small email validation via the PHP filter_var () method. Then we sent the message via the mail() method.

Next Create the Contact Form to send a message.

<form id="mycontactform" action="" method="post"><label for="name">Name:</label>

<input id="name" type="text" name="name" />

<label for="email">Email:</label>

<input id="email" type="text" name="email" />

<label for="message">Message:</label>

<textarea id="message" name="message"></textarea>

<input id="submit" type="button" value="send" />
<div id="success" style="color: red;"></div>

As you can see by the code above we created a very simple form to send a message with, nothing big about it at all.

Next we create the jQuery Ajax code to post the form details to our PHP code

<script type="text/javascript" src=""></script><script type="text/javascript">


$.post("send.php", $("#mycontactform").serialize(),  function(data) {   });

$('#success').html('Message sent!');



Here we call the jQuery code directly from the jQuery code library. Then write code to run when the page is done loading.

We use an onclick event which sends the form data to our send.php file which contains our PHP code to handle the email sending. We then set a success message and hide it again.

Update 03 Dec 2012

Hi Guys,

I've made some changes to the code as requested.

The response of the jQuery is now working and you will get a notice if you insert the incorrect email. Here is the html and jquery

<!DOCTYPE html>
<script src=""></script>


$.post("send.php", $("#mycontactform").serialize(),  function(response) {
return false;



<form action="" method="post" id="mycontactform" >
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="message">Message:</label><br />
<textarea name="message" id="message"></textarea><br />
<input type="button" value="send" id="submit" /><div id="success" style="color:red;"></div>

Here is the new PHP code.

// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = '';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From:' . "\r\n";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
echo "Invalid Email, please provide an correct email.";

You can download the new code now.

Demo Link

Download the code from here:  Contact Form Code

If you’ve liked this tutorial or if you have some questions let me know in the comments section below. Please like the article?

Related Posts:

  • rss
  • email
  • rss
  • email
I'm a full time PHP developer and I just love all things web related. If you need help I'm your guy.

66 Responses to For The Newbies: A simple PHP Contact Form Using Ajax To Send Email

  1. Anjibattu says:

    i think your demo is not working properly…

  2. Morné says:

    Thanks for letting me know but be more specific so that I can fix it :)

  3. Morné says:

    Ok I’ve fixed the demo, please do a hard refresh on your side to clear your cache

  4. I can get more specific – the code spits out a success whatever you put into the form. You have some error code at the end of the PHP, but no error message is ever deliver to the user. How can we have the error code show up and disappear just like the success code does?

  5. Morné says:

    Hi Michael,

    Thanks for letting me know, You are correct in saying that the error code is not showing.

    The reason why this is happening is because I’m using ajax and forgot to use the response that is returned from the PHP script to show the error message.

    You have a good eye :) thanks again for letting me know, this is what happens when you code late at night.

    Will fix this tonight.

  6. Jeetendra S Ahuja says:

    How to send form data to php page using send method of AJAX.

  7. Would you be so kind to write the code to obtain the response from mailing code?

  8. Morné says:

    Hi Alexander,

    Will do it as soon as I get some time. Will try for this week to do some changes and update the post with new code.

    Please keep an eye out for the updated code.


  9. aswin selvakumar says:

    I wrote a simple code for Ajax..


    var xmlHttpRequestObj = false;
    if(window.ActiveXObject) {
    xmlHttpRequestObj = new ActiveXObject(“Microsoft.XMLHTTP”);
    else if (window.XMLHttpRequest){
    xmlHttpRequestObj = new XMLHttpRequest();

    function getData(dataSource,divId)
    if(xmlHttpRequestObj) {
    var obj = document.getElementById(divId);“GET”,dataSource);

    xmlHttpRequestObj.onreadystatechange = function()
    if(xmlHttpRequestObj.readyState == 4){

    obj.innerHTML = xmlHttpRequestObj.responseText;


    Ajax demo

    This will go and message will appear!!

    And the sespective php code is

    But when i click the button nothing is happening.. Pleaseeeeeee help me

  10. Morné says:

    Hi Aswin,

    I’m not familiar with the way Microsoft’s ActiveX objects work. This is not for PHP by the looks of the code.

    What I do notice is that you have a JS variable called divId but it’s not declared anywhere in the code above. Also you are using an old way of using JavaScript onclick events and Your input fields have no id’s to target.

    Have a look here to see the correct way to do modern onclick events with JavaScript

    Hope this helps :)

  11. aswin selvakumar says:

    Hi Morne,
    I have this php code.

    And I tried using Firefox instead of IE..
    I got an error as “No element found”.. and it’s pointing to the first line
    What this error means..

  12. Morné says:

    Hi Aswin,

    This is not PHP it’s javascript.

    This is one of the answers I found on stackoverflow:
    “Firefox is expecting to get something it can parse as XML back, and throwing an XML parsing error when it gets an empty response.”

    Here is the link.

    Also have a look at these answers

  13. This tutorial has been an amazing help! Thank you.

    Is there anyway to clear the form once the form is successfully submitted?

  14. Morné says:

    Hi Maggie,

    I’m glad this has been an help.

    You can use the following code

    $(“.reset”).click(function() {
    $(this).closest(‘form’).find(“input[type=text], textarea”).val(“”);

    to clear all form fields, just add it after this part $(‘#submit’).click(function(){

    That should work.

    If you are interested in learning something new, than I’m open to suggestions. Just contact me and I will do a tutorial on it.

    Thanks for the comment :)

  15. That didn’t work. :-/ Am I supposed to assign something a class named “reset”?

  16. I have a tutorial idea! Is it possible to make a math captcha with PHP? I’ve seen those around a few places and they are less annoying than letters ones.

  17. Morné says:

    Hi sorry about that, use this.

    $(this).closest(‘form’).find(“input[type=text], textarea”).val(“”);

    I was to quick on copy and paste :) You only need the code above. Copy it just underneath the $(‘#submit’).click(function(){ part.

    It will look for the closest form element and clear the fields.

  18. Janek Raidal says:

    Hi, great work. One question, how do you turn off the valid email address check? It is pretty strict and i can’t take that chance that client writes me a letter and because i’m using the “clear fields after submit”, all text disappears if clients e-mail is “weird” and returns error…

    Or maybe a function, that if is wrong email, it won’t clear all fields and all fields get cleared only when successful submit?

  19. Janek Raidal says:

    oops, went double posts

  20. Sathya Prakash Moparthi says:

    hey Morné thanks for the tutorial. I am having a serious problem with my PHP project. Unable to make a Idea work. Please will you help me.

  21. Morné says:

    Hi Sathya,

    Get in touch with me through my contact form. I can help you from there :)

  22. bob says:

    Nice Work!

    you can find another contact form here

    hope it would be useful

  23. Ahmad Baidrul Hisyam Abdul Jam says:

    Hi, I’m also working on another variation of the similar code. I obtain it form a template that I just purchased. However I made some adjustment.

    My form page looks like this (contact.html):

    Name (required)

    Please enter your name !
    Email (required)

    Please enter your email address ! Please enter a valid email address !

    Please enter message !

    I decided to use another ajax jquery (contact.js):

    jQuery(function() {
    jQuery(“.contactButton”).click(function() {
    // validate and process form
    // first hide any error messages

    var name = jQuery(“input#contactName”).val();
    if (name == “”) {
    return false;
    var email = jQuery(“input#contactEmail”).val();
    if (email == “”) {
    return false;

    var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;
    if(!emailReg.test(email)) {
    return false;

    var msg = jQuery(“textarea#contactMessage”).val();
    if (msg == “”) {
    return false;

    var dataString = ‘name=’+ name + ‘&email=’ + email + ‘&msg=’ + msg;
    //alert (dataString);return false;

    type: “POST”,
    url: “php/mail.php”,
    data: dataString,
    success: function() {
    jQuery(‘#successMessage’).html(“Thank you for contacting us!“)
    .append(“We will be in touch soon.”)
    .fadeIn(1500, function() {
    return false;

    Right now I’m wondering how to do the (mail.php)

    Could you please help me?


  24. Morné says:

    Hi There,

    Sorry for only getting back to you now. It’s php’s own email filter that does the checks, the filter_var part is where all the action happens. You can remove that if you want.


  25. Lee says:

    Is it possible to send HTML in the email to format it nicely?

  26. Ravi says:

    Hi, Iam getting message email sent but iam not getting email to my mail id.
    i need to change any code in php file like to mail id and from mail id.

  27. Morné says:

    Hi Ravi,

    Which email address are you using, gmail, yahoo or your own domain? It could be that your servers ip is getting blocked for sending mail or it could be that your mail function is not working on the server.

    Also check your spam box.

  28. Morné says:

    Hi Lee,

    Sorry for only replying now, yes it’s possible to send HTML format. There are lots of tutorials on the web to do that.

  29. Morné says:

    Hi Ahmad,

    Sorry for only replying now. What I can make out is that you would need to change the mail.php to match the field names to be able to send it off, otherwise it will not work properly.

  30. Morné says:

    Wow, I don’t know how I missed this comment. Yes it’s totally possible. I will look in to this and create a tutorial.

  31. orczy says:

    Hi, i tried your code, but firefox consol said: response is not defined.




    $.post(“callback.php”, $(“#callback”).serialize(), function(response) { });
    $(‘#success’).css(‘background’, ‘#189000′);
    return false;

    echo ‘Your email was sent!';

    Could you please help me?

  32. Morné says:

    Hi there,

    Do you have this file callback.php somewhere? You will need that to get a response.

  33. Girish Gowda says:

    Thank you man, saved my time…

  34. Morné says:

    Glad it’s working for you :)

  35. mariano says:

    hi. I tried your code. it only works for the first sending. if I am filling out the form fields again, it continues to give me the message but can not quite place sending more emails after the first

  36. mariano says:

    no sorry, maybe is a problem of server, sometimes sending and sometime not

  37. Bobby Cheema says:

    Hi Morne , I am not a programmer but love to go through php and javascript code ,I work in retail and I try to write small programs to make my life easy , I have a simple PHP reconsilation script that adds up the cents and dollars at the end of the day it asks for input and then submits that to php and then u get the result however i want a way so that you start getting the result as soon as you add the next entry , hope you understand what i am trying to say sort of simple calculator that adds up as soon as the number is filled in . i couldnt find any tutorial to do that



  38. Morné says:

    Hi Bobby,

    You can send me the code you have via my contact form. I will have a look and guide you from there.

  39. Morné says:

    Hope you got it solved?

  40. guntur says:

    Hi Morne,
    Need some help.
    I have tried to run this code in my mechine.
    But Unfortunatelly, I found the issue, as below:
    Warning: mail() [function.mail]: Failed to connect to mailserver at “” port 25, verify your “SMTP” and “smtp_port”
    How should I do to modify the smtp code?
    Currently, the smtp code as folow:
    [mail function]
    ; For Win32 only.
    SMTP = localhost;
    smtp_port = 25
    And I want implement this code to my company email,
    Kindly let me know.

  41. Morné says:

    Hi Guntur,

    The issue you have is because you are trying to send mail from you localhost setup. Your php mail function will only work from a live server unless you setup your localhost environment to be able to send mail from your own pc.

    I do recommend getting a cheap hosting account from hostgator (affiliate link, helps me keep this site running)

    I do know that with my latest install of xampp on my pc I could not get it to send mail from localhost.

    It’s always good to have a live testing server along side your localhost server :)

  42. htmlbooknet says:

    I have used this code but getting mail in spam in gamil, please reply

  43. Morné says:

    Hi there,

    You would still need to add some form of captcha. This form is not for catching spam it’s just an example of an ajax contact form.

  44. srinivasan says:

    Hi can u use some ajax loader showing when sending the form for processing…and after request is done form submitted the ajax loader should vanishes, can u do this please

  45. dulf says:

    hi.. ive tried your code but this is the output, then i check my email no email comes
    Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:xampphtdocscontact_form_php_ajaxsend.php on line 14, thank you ..

  46. Morné says:

    Hi Dulf,

    The issue here is that your local xampp server is not able to send mail from your pc. You would need to open some ports to be able to send mail from you Own pc. Can’t remember how to do this as I’ve done this before ages ago.

    Best would be to rent a cheap server somewhere to test your code on a live environment. I recommend Hostgator but you are welcome to try it somewhere else.

    This might also help you setup your mail on your pc

  47. Rohan madusanka says:

    hi.. please tell me that ,can i try these codes using wamp server

  48. Morné says:

    Hi Rohan,

    The ajax part will work on a local server. But sending email from localhost usually does not work unless you set it up to be able to send email from you own pc.

  49. Rohan madusanka says:

    here php and html codes we have to put separately like .php and .html so like that how we put jquerry code please tell me Mr Morne

  50. Thana says:

    Hi , Thanks for your code it’s so helpful .
    I have one Question .. i want when i send the email the receiver one can see the email in the inbox not in the junk how I can do that????

  51. Morné says:

    Hi Thana,

    Usually if it’s a contact form and the mail is coming to yourself from the contact form then you just need to mark the email address it’s coming from not as spam and all future mails will come to your inbox

    If you need to send mail to someone by using an action ( for example clicking on the send button ), you would need to use a service that provides a transactional email service. I’m using this service Mandrill It’s a service by Mailchimp.

    Hope this gives you some direction.


  52. Thana says:

    Ok thanks .. I want to change the message to my Varibals i but them like the name

    and i put it in the message down all my Varibals but it say that it’s invalid email

    so i have to not change the message or how i send my other form things beside the Varibals in the example

  53. Morné says:

    Could you please paste some code here so that I can see? Thanks

  54. Thana says:

    this is in the send.php

    // Here we get all the information from the fields sent over by the form.

    $content_introduction = $_POST[‘content_introduction2′] ;
    $content_emai = $_POST[‘content_email’] ;

    $to = ‘';
    $subject = ‘the subject';
    $message = ‘FROM: ‘.$content_introduction.’ Email: ‘.$content_emai.’Message: ‘;
    $message = $message.’yemen /”.
    : $content_dat
    country: $countr
    city: $stat
    : $content_checkbox
    : $content_introduction
    : $content_autho
    : $content_authorsummar
    : $content_sourc
    : $content_detai
    : $content_deta
    : $content_emai
    : $content_detail
    : $content_det
    : $content_file_fullname

    $headers = ‘From:‘ . “rn”;

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
    mail($to, $subject, $message, $headers); //This method sends the mail.
    echo “Your email was sent!”; // success message
    echo “Invalid Email, please provide an correct email.”;

    even i put all varibals ..

  55. Morné says:

    You’ve got quite a few syntax errors in that code, that is why it’s not working. Look at the php errors that the server is reporting back to you.

  56. tai says:

    hi..i want to ask how to send email after three days based on date in database?

  57. Morné says:

    Hi Tai,

    If you’ve written a php script to send out mail. Then all you would need is to have a cron job running daily to check the database and if it’s time to send the email the run the mail function.

  58. Thana Al-amri says:

    Hi again .. the code was correctly all time ..

    from one month or more

    now there is a problem .. the email not send and my insert to the database from the form not work too ..

    when i delete this line

    $.post(“send.php”, $(“#mycontactform”).serialize(), function(data) { });

    the inserting work .. and the email not send

    why it’s change while it was working before one month ????

    could u tell me please

  59. Onyxious says:

    Hi, thanks for this helpful code.
    But how can you implement HTML email with logo and table just to make the email to have good looking. #picturedaworldifferently @onyxious_creats

  60. kunal singh says:

    hi ,
    mail code run on server
    but it doenot run with wamp server

  61. Steven Ludmon says:

    Thanks for a great post, I’m using the php mail function in a web app and your code is simply perfect!
    Cheers from Australia 😉

  62. Troy Sanders says:

    Any advice on how to email visitors geolocation to oneself or write to a file?

  63. Matic Podgornik says:

    hey guys. thanks for your tutorial. I somehow get the “Invalid mail” error. Can anybody help me with that?

  64. Cecilio Lanz says:

    I´m using the same code but the mail is not arriving to my inbox

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>