Skip to content

Instantly share code, notes, and snippets.

@cbejensen
Last active October 30, 2018 17:51
Show Gist options
  • Save cbejensen/edb8ea01e0f7ca33ad30401c84495cc8 to your computer and use it in GitHub Desktop.
Save cbejensen/edb8ea01e0f7ca33ad30401c84495cc8 to your computer and use it in GitHub Desktop.
Simple Form with Ajax
(function() {
const forms = document.querySelectorAll('.js-contact-form');
let statusElems = [];
let status = "";
forms.forEach(function(form) {
if (!form) return;
form.addEventListener('submit', function(e) {
e.preventDefault();
const xhr = new XMLHttpRequest();
xhr.open('POST', 'submit.php');
xhr.send(new FormData(form));
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.response === 'sent') {
displaySubmitStatus(
'Thank you! We will get back to you soon!',
true
);
} else if (xhr.response === 'incomplete') {
displaySubmitStatus('Please fill in all required fields.', false);
} else {
displaySubmitStatus(
'Sorry, something went wrong. Please refresh and try again.',
false
);
}
}
};
});
});
function displaySubmitStatus(msg, sent) {
const newStatus = sent ? 'success' : 'error';
// if this is the first submit, create status element(s)
if (!statusElems.length) {
const newElem = document.createElement('div');
newElem.classList.add('form-status', newStatus);
forms.forEach(function(form) {
form.appendChild(newElem);
statusElems.push(newElem);
});
}
statusElems.forEach(function(e) {
// if this is not the first submit or status is different
// change status class
if (status && newStatus !== status) {
e.classList.remove(status);
e.classList.add(newStatus);
}
e.innerHTML = msg;
return true;
});
status = newStatus;
}
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Simple Form</title>
</head>
<body>
<form class="contact-form">
<input required name="name" placeholder="Name" type="text">
<input required name="email" placeholder="Email" type="email">
<input name="phone" placeholder="Phone" type="tel">
<select required name="type">
<!-- value="" on default so it will throw an error in PHP if not changed -->
<option value="" disabled selected>Select Type...</option>
<option>General</option>
<option>Technical</option>
<option>Warranty</option>
</select>
<textarea name="msg" placeholder="Message"></textarea>
<button type="submit">Submit</button>
</form>
<script src="./form-handler.js"></script>
</body>
</html>
<?php
$name = filter_field($_POST['name']);
$email = filter_field($_POST['email']);
$phone = filter_field($_POST['phone']);
$type = filter_field($_POST['type']);
// preserve line breaks for textarea
$msg = nl2br(filter_field($_POST['msg']));
// make sure required fields have been filled out
if (!empty($name) && !empty($email)) {
$current_url = get_current_url();
$data = '
<h1>Form Submission</h1>
<h2>From: ' . $current_url . '</h2>
<p><strong>Name</strong><br/>' . $name . '</p>
<p><strong>Email</strong><br/>' . $email . '</p>
<p><strong>Phone</strong><br/>' . $phone . '</p>
<p><strong>Type</strong><br/>' . $type . '</p>
<p><strong>Message</strong><br/>' . $msg . '</p>
';
$to = "CHANGEME";
$subject = "Form Submission";
$headers = "From: $to\r\n";
$headers .= "Reply-to: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8\r\n";
if (mail($to, $subject, $data, $headers)) {
echo 'sent';
} else {
echo 'unsent';
}
} else {
echo 'incomplete';
}
function filter_field($field){
// Restores the added slashes (ie.: " I\'m John " for security in output, and escapes them in htmlentities(ie.: &quot; etc.)
// Also strips any <html> tags it may encounter
return htmlentities(trim(strip_tags(stripslashes($field))), ENT_NOQUOTES, "UTF-8");
}
function get_current_url() {
$url = ( isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ) ? 'https' : 'http';
$url .= '://' . $_SERVER['SERVER_NAME'];
$url .= in_array( $_SERVER['SERVER_PORT'], array( '80', '443' ) ) ? '' : ":" . $_SERVER['SERVER_PORT'];
$url .= substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '/') + 1);
return $url;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment