Skip to content

Instantly share code, notes, and snippets.

@kunalvarma05
Last active May 5, 2022 15:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save kunalvarma05/4181040 to your computer and use it in GitHub Desktop.
Save kunalvarma05/4181040 to your computer and use it in GitHub Desktop.
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
Copy link

lsaul 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?

Copy link

ghost commented Jan 16, 2019

This code will never work... :'D

@Bablubaghel
Copy link

Great :)

@hatry4
Copy link

hatry4 commented May 5, 2022

Does this work for git pages??

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