In this tutorial we will be creating a simple Ajax Contact form using jQuery and PHP. Because the best thing about Ajax is that users don’t have to reload the page every time in order to validate empty fields or to send emails, they can simply click send button and results are displayed instantly on the screen.
You can find links to demo page and downloadable sample at the bottom of this page. With few tweaks here and there, you should be able to integrate this contact form in your website. This tutorial is intended for beginners and if you have questions please do let me know by commenting.
When user wants to contact you, s/he will first see your contact page. It is totally up to make it look cool and presentable. In example below you can see HTML code for the form. Since we are making Ajax based contact form, we don’t need to warp the fields with <form></form>, we can simply use jQuery .val() to collect the values from the input fields.
The CSS code is located in a separate file called style.css, include this file within the <head></head> section of HTML page, and modify the file as needed to make your contact page look interesting.
The first thing to learn about jQuery is $(document).ready(). If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded. So we will write all our jQuery code inside $(document).ready() function as shown in example below.
Below is our final jQuery code for the Contact form. As you can see we have placed all code inside $(document).ready(). Right after that we have $(“#submit_btn”).click(), which gets triggered when user clicks submit button on the contact form, within this function we collect, validate and send user data to contact_me.php PHP file using jQuery $.post() method, which is a shorthand Ajax function equivalent to jQuery $.ajax(). I am sure the comment lines in the code below will help you understand the it more clearly.
Below is our PHP code, this file (contact_me.php) is needed to respond to contact page Ajax requests. As soon as user clicks submit button, jQuery validates empty field and sends data to this page. Here we check $_POST variables, sanitize using PHP filter_var() to remove any harmful characters in the string, then further validate them, and then send the mail to the recipient. On success, we need to output success message or the errors if it fails.
That’s it! we now have a neat looking Ajax based contact form. I do want to see it working live in one of your website, so if you are using this example, please do comment and share your links here and good luck!