Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AJAX Contact Form with PHP
<!DOCTYPE HTML>
<html>
<head>
<title>Welcome to my Website</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="send.js"></script>
</head>
<body>
<h1>A Simple AJAX Contact Form</h1>
<form method="post" action="" id="contact_form">
<input type="text" name="name" placeholder="Name" id="name">
<input type="email" name="email" placeholder="Email" id="email">
<textarea name="message" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send">
</form>
<span id="notice" style="display:none;">Thanks. We will get back to you soon.</span>
</body>
</html>
<?php
//Get the Form Values
if (isset($_POST['name']) {
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])){
return FALSE;
}else{
//Make Variables Safe
mysql_connect('localhost', 'root', 'password');
$name = mysql_real_escape_string(trim($_POST['name']);
$email = mysql_real_escape_string(trim($_POST['email']);
$message = mysql_real_escape_string(trim($_POST['message']);
$query = 'INSERT INTO contacts ('name', 'email', 'message') VALUES("'.$name.'", "'.$email.'", "'.$message.'")';
$result = mysql_query($query) or die(mysql_error());
}
}else {
header('Location: index.htm');
}
?>
$('#contact_form').submit(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "save.php",
data : dataString,
cache : false,
success : function() {
$("#contact_form").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
@lsaul

This comment has been minimized.

Copy link

commented Jan 20, 2014

Looks like "mysql_real_escape_string" will become deprecated (http://us2.php.net/mysql_real_escape_string). How should this code be updated?

@PrestaShark

This comment has been minimized.

Copy link

commented Jan 16, 2019

This code will never work... :'D

@Bablubaghel

This comment has been minimized.

Copy link

commented May 12, 2019

Great :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.