A contact form is something that is essential for any website. Not having a contact form is never a good idea. Now, in order to make a contact form, you will be required to develop the front-end (that is visible to the user) and also develop the back-end (that is not visible to the user, but sends the actual email). There are various technologies you can use as the back-end, but I prefer using PHP for all my projects. So, for this tutorial, I would use PHP as the back-end and HTML as the front-end. In this tutorial I will teach you how to make a contact form using AJAX and PHP.
Earlier, I have shared a few tutorials on creating contact forms, using PHP, and using Google Docs/Drive. In today’s tutorial, I will teach you how to create a contact form using PHP and AJAX. If you’re wondering how this tutorial will be different from the one where I used PHP only, let me explain it to you. Have you ever seen a web page with a contact form where when you press submit or send, it gives you a message that the message has been sent, but does not reload any other page to do so? If yes, then this is the tutorial that will help you create such a contact form page. If not, head over to the Slash Coding contact page, and drop in an email to me. You’ll see what I’m talking about.
- Learn how to create a guest book using PHP
Now, let’s get started with the actual tutorial, and help you create a contact form for your website using AJAX, PHP and HTML.
HTML For Contact Form
<!DOCTYPE HTML> <html> <head> <title>Contact form using AJAX and PHP</title> </head> <body> <form name="contact-form" onsubmit="submitForm()" method="post"> <input type="text" placeholder="Enter your name" name="name"><br/><br/> <input type="email" placeholder="Enter your email Address" name="email"><br/><br/> <textarea placeholder="Enter your message here" name="message"></textarea><br/><br/> <button type="submit" >Send Message</button> </form> </body> </html>
PHP for Contact Form using AJAX
<?php $name = $_POST['name']; $email = $_POST['email']; $msg = $_POST['msg']; $to = '[email protected]'; $subject = 'Email from Contact Form (Slash Coding)'; $message = 'Name: '.$name. "\r\n". 'Email: '.$email. "\r\n".'Message: '. $msg; $header = 'From: '. $name . '<[email protected]>'. "\r\n" . 'Reply-To: '.$email . "\r\n". 'X-Mailer: PHP/'.phpversion(); if(mail($to,$subject,$message,$header)) echo 'Email Sent Successfully'; else echo 'Email Failure'; ?>
Well, that’s it. You are done with this AJAX contact form. I hope this tutorial helped you learn something new and you will incorporate it in your next project. Feel free to get in touch via the contact form or the comments section below. I will be happy to answer all your queries. You should sign up for our updates on your Social Media profiles, by following us or liking us on various Social Media platforms. You should also subscribe to the latest and greatest posts via email alerts.