Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple Asynchronous Contact Form with jQuery and PHP

Simple Ajax Contact Form with jQuery and PHP


  • index.html
  • style.css
  • js.js
  • mailer.php


  • Copy code or files to your project and change $to = ""; in mailer.php to your email address.
  • Edit and style to suit your needs.

If you have any questions or innovations please leave me a comment.

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Contact Form</title>
<link rel="stylesheet" href="style.css"/>
<form action="" id="form">
<label for="email">Email:</label>
<input type="text" name="email" id="email" placeholder=""><br>
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" placeholder="subject"><br>
<label for="message">Message:</label>
<textarea name="message" id="message" placeholder="message"></textarea><br>
<button name="submit" id="submit">Send</button>
<label id="info"></label>
<script src=""></script>
<script src="js.js"></script>
$(document).ready(function() {
var form = $('#form'),
email = $('#email'),
subject = $('#subject'),
message = $('#message'),
info = $('#info'),
submit = $("#submit");
form.on('input', '#email, #subject, #message', function() {
$(this).css('border-color', '');
submit.on('click', function(e) {
if(validate()) {
type: "POST",
url: "mailer.php",
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
function validate() {
var valid = true;
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email.val())) {
email.css('border-color', 'red');
valid = false;
if($.trim(subject.val()) === "") {
subject.css('border-color', 'red');
valid = false;
if($.trim(message.val()) === "") {
message.css('border-color', 'red');
valid = false;
return valid;
if($_POST) {
$to = ""; // your mail here
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$body = "Message: $message\nE-mail: $email";
if(@mail($to, $subject, $body)) {
$output = json_encode(array('success' => true));
} else {
$output = json_encode(array('success' => false));
label {
width: 200px;
display: block;
input, textarea {
width: 200px;
margin: 5px 0;
border: 1px solid #CCC;
p {
width: 200px;
Copy link

ghost commented Sep 25, 2019

Thank you for posting this, been searching for a long time for a neat solution (i.e. without using third party servers)
Works perfectly ...
Regards chiprobot

Copy link

caio-2k commented Aug 18, 2020

should you can me explain what the function done do? ty for the sharing man 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment