How to create a simple HTML contact form with Ajax & PHP

There are so many times we don’t want to use any PHP file (say contact.php) directly for our HTML websites to process contact form rather we prefer to use HTML contact page (say contact.html). It is not a hard task, we can do this by using Ajax or jQuery. In this tutorial, I am describing the easiest way to do the same.
The form will be in any HTML extension page with validation. What we need a separate PHP file for parsing email function only.

Here are the screen shots of the forms.

ajax-contact-form-basic
ajax-contact-form-validated

Step 1: Create an HTML page (contact.html) and write the form code with jQuery library CDN and validation script file adding.

Step 2: Add a JS file for the form validation and Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php .

Step 3: Create a php file as email.php and write down the main PHP mail function.

Demo | Download


Posted

in

by

Tags:

Comments

26 responses to “How to create a simple HTML contact form with Ajax & PHP”

  1. Bluebell Developer avatar
    Bluebell Developer

    This is eaxtly what I was looking for some days ago. Tested the script and it works like a champ. Thanks.

  2. Someone avatar
    Someone

    Not good idea without server side validation!

    1. azhari1991 avatar
      azhari1991

      actually you can use jquery form validation plugin… there are many out there if you wanna find it…

      1. Sanjay Bhowmick avatar

        I know that, but I tried to give some coding idea of the developers in my post.

  3. Jessica Guillermo avatar
    Jessica Guillermo

    Where do I input the receiver’s email in the email.php? Right now it’s sending to the sender’s email. To and from.

    1. Sanjay Bhowmick avatar

      In your email.php file you have a line as
      $to = $_REQUEST[’email’]; //Recipient’s E-mail
      Write your email id in the place of $_REQUEST[’email’];
      So the modified line will look like this

      $to = ‘yourname@gmail.com’; //Recipient’s E-mail

  4. Maggie Jones avatar
    Maggie Jones

    Hi, Thank you so much for this. This is a dream come true. I just want to humbly give one tip to people like me who might have a success message, but see that the email is not being sent. This could be due to the “from” header. Some webhosts block “spoofing”. Remove the..

    $headers .= “From: ” . $_REQUEST[’email’] . “rn”; // Sender’s E-mail

    …from email.php and it will work again. I think the other way to solve this is to edit your php.ini file. Sounds scary 🙂 Here’s some info here:

    http://wiki.dreamhost.com/Sender_Domain_Policy_and_Spoofing#Sender_domain_policy._What_is_it.3F

    1. Sanjay Bhowmick avatar

      Hi Maggie, you are right. I just used a sample PHP mail function in the email.php file. The developer can change the email function fully as per server. Can be used SMTP email instead. So, the email.php was not my point of concern. Users have own choice to customize this replacing the header info. Thanks for sharing your knowledge.

  5. Sharmelon avatar
    Sharmelon

    Hi, thanks for this great post. It is indeed dream come true for me. I built an enquiry form on a site using the process here. Check the site >> http://www.sadaworld.com << I encountered some issues initially which i was able to resolved. For a while, i could send and receive mail successfully until everything changes, but i don't know what went wrong. Now mail aren't delivered with the validation script. When i hit the send button, the "sent successfully" box wouldn't come up and mail don't get sent. The problem is with the script, because when i removed the script using only the email.php, the mail was sent and received successfully. Meanwhile, the validation works well when errors occur.
    Here is my script, please review. I will be glad for your professional help and advice here.

    ………………………………………………………………………………………………………………………………

    $(document).ready(function(){
    $('#send_message').click(function(e){

    //Stop form submission & check the validation
    e.preventDefault();

    // Variable declaration
    var error = false;
    var name = $('#name').val();
    var email = $('#email').val();
    var subject = $('#subject').val();
    var message = $('#message').val();

    // Form field validation
    if(name.length == 0){
    var error = true;
    $('#name_error').fadeIn(500);
    }else{
    $('#name_error').fadeOut(500);
    }
    if(email.length == 0 || email.indexOf('@') == '-1'){
    var error = true;
    $('#email_error').fadeIn(500);
    }else{
    $('#email_error').fadeOut(500);
    }
    if(subject.length == 0){
    var error = true;
    $('#subject_error').fadeIn(500);
    }else{
    $('#subject_error').fadeOut(500);
    }
    if(message.length == 0){
    var error = true;
    $('#message_error').fadeIn(500);
    }else{
    $('#message_error').fadeOut(500);
    }

    // If there is no validation error, next to process the mail function
    if(error == false){
    // Disable submit button just after the form processed 1st time successfully.
    $('#send_message').attr({'disabled' : 'true', 'value' : 'Sending…' });

    /* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
    $.post("email.php", $("#contact_form").serialize(),function(result){
    //Check the result set from email.php file.
    if(result == 'sent'){
    //If the email is sent successfully, remove the submit button
    $('#submit').remove();
    //Display the success message
    $('#mail_success').fadeIn(500);
    }else{
    //Display the error message
    $('#mail_fail').fadeIn(500);
    // Enable the submit button again
    $('#send_message').removeAttr('disabled').attr('value', 'Send');
    }
    });
    }
    });
    });

    1. Sanjay Bhowmick avatar

      If you email me [info at wavesdream dot com] the source code of then website in zip format if the size is not large then I can check and fix the issues.

  6. Graham avatar

    Hi. Thanks for this. Like others it is just what I need. Just one thing though, having successfully sent the message it would be good if the form was no longer displayed. Is there some way this can be done?

    1. Sanjay Bhowmick avatar

      Graham, it is possible to hide the form after successful form submission. You can check the call back function and for successful message you can write a script which will make the form css as ‘disply:none’.

  7. surebzz avatar
    surebzz

    Can we test on localhost?
    I am getting error on clicking send

    Notice: Undefined variable: message in D:xampphtdocsurbanicemail.php on line 6
    sent

    1. Sanjay Bhowmick avatar

      You can not send email from localhost. You have to upload files in a server where PHP email function is supported.

      1. surebzz avatar
        surebzz

        testing live…on submit it shows new page with “sent”…doesn’t use ajax..also I do not receive the email

        1. Sanjay Bhowmick avatar

          Send your files as a zipped format. I will check and let you know what the issue for. But it will take time, I will check in some free time.

  8. mery avatar
    mery

    fimaly, i get it ^_^
    but .. another questions
    how can i make the field empty after send msg?? ‘^_^

  9. Making You Smile avatar

    That is a grat ttip particularly to those new to the blogosphere.
    Brief but very accurate information… Appreciate your sharing this one.
    A must read article!

  10. Elias avatar
    Elias

    Works great with some adjustments 😉 🙂

  11. Elias avatar
    Elias

    Question: How to prevent someone to access the mail.php directly? I’ve tried the form with disabled JS which sends out blank emails. How to fix this? Should there be a check in the mail.php as well to see if all fields are filled?

  12. Rahul Shinde avatar

    Hi Sanjay,

    It look great what i wanted but it not working on my domain.

    1. Sanjay Bhowmick avatar
      Sanjay Bhowmick

      If you share the link of the page or send me the file, I can check.

  13. zlodziejb avatar

    Oh, it’s look awesome but I have problem. When I or somebody click “submit” ajax doesn’t work and script move to new page with “sent” ;(

    1. zlodziejb avatar

      Ok, don’t know how but i fixed this problem 🙂

      1. Sanjay Bhowmick avatar
        Sanjay Bhowmick

        You can email me [me@sanjaybhowmick.com] your script to look into.

      2. Tom avatar
        Tom

        How you fixed this? I also get “Sent” on an empty page after mail is sent.

Leave a Reply

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