How to Create Contact form using Ajax, PHP and MySQL

Ajax form submission is better and fast way to submit form without page loading .It’s make a nice experience to your users. Below we have written a tutorial on how to submit a contact form with jquery ajax . You can also consider this as a PHP, ajax registration form . First of all we have to create a html file ,with below html codes. You may also like Contact Form Web Application Tutorial Ajax HTML5 PHP.

HTML Code

<h1>Contact Form</h1>
<form method="post"  onsubmit="return save();">
    <table align=center>
        <tr>
            <td>Enter Your Name : </td><td><input type="text" id="sender_name" name="sender_name"></td>
        </tr>
        <tr>
            <td>Enter Your Email : </td><td><input type="text" id="sender_email" name="sender_email"></td>
        </tr>

        <tr>
            <td>Message : </td><td><textarea id="message" name="message"></textarea></td>
        </tr>
    </table>
    <p><input type="submit" name="send_mail" value="SUBMIT FORM"></p>
</form>

jQuery Code

<script type="text/javascript">
    function save()
    {
            var name=$("#sender_name").val();
            var email = $("#sender_email").val();
            var message = $("#message").val();
            if (name != "" && email != "" && message != "")
            {
                $.ajax
                ({
                    type: 'post',
                    url: 'ajax.php',
                    data: {
                        submit_contact: "submit_contact",
                        name: name,
                        email: email,
                        message: message
                    },
                    success: function (response) {
                        if (response == "submitted")
                        {
                            document.getElementById("contact_form").innerHTML = "Thanks For Contacting Us We Will Contact You Soon";
                        }
                    }
                });
            } else
            {
                alert("Please Fill All The Details");
            }

            return false;
        }
</script>

PHP Code (ajax.php)

<?php
if(isset($_POST['submit_contact']))
{
    $name=$_POST['name'];
    $email=$_POST['email'];
    $message=$_POST['message'];

    mysql_query("insert into contact (name,email,message)values('$name','$email','$message')");
    echo "submitted";
}
?>

Leave a Reply

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