Created
April 23, 2018 00:41
-
-
Save pbzona/c183566bb48742099801072bc0afda4d to your computer and use it in GitHub Desktop.
Serverless contact form with inline success message
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>My Contact Form Microservice</title> | |
<style> | |
/* It's not pretty, but it'll do :) */ | |
input, | |
textarea { | |
display: block; | |
margin: 20px; | |
} | |
</style> | |
</head> | |
<body> | |
<form id="serverless-contact-form"> | |
<input type="text" name="email" placeholder="Email Address" class="form-email"> | |
<input type="text" name="subject" placeholder="Subject" class="form-subject"> | |
<textarea rows="5" cols="40" name="message" placeholder="Your message here..." class="form-message"></textarea> | |
<input type="submit" name="submit" value="Submit" class="form-submit"> | |
</form> | |
<!-- Here we use an empty element to display our future success/error message. Give it an id for easy targeting in the JS --> | |
<p id="confirmation"></p> | |
<script type="text/javascript"> | |
document.getElementById('serverless-contact-form').addEventListener('submit', sendDataToLambda); | |
function sendDataToLambda(e) { | |
e.preventDefault(); | |
var formEmail = document.querySelector('.form-email').value; | |
var formSubject = document.querySelector('.form-subject').value; | |
var formMessage = document.querySelector('.form-message').value; | |
var endpoint = 'https://your-api-gateway-endpoint.com/ContactFormLambda'; | |
var body = { | |
email: formEmail, | |
subject: formSubject, | |
message: formMessage | |
} | |
var lambdaRequest = new Request(endpoint, { | |
method: 'POST', | |
mode: 'no-cors', | |
body: JSON.stringify(body) | |
}); | |
// Grab the element we created above (below the form) ^^^ | |
var confirmation = document.getElementById('confirmation'); | |
// Make the request... | |
fetch(lambdaRequest) | |
.then(response => { | |
// If the request succeeds, put confirmation text into our element: | |
confirmation.innerText = "Thanks for your message! We'll be in touch soon."; | |
}) | |
.catch(err => { | |
// If there's an error, ask them to try again | |
confirmation.innerText = "Oops! Something went wrong, please try again."; | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment