Simple contact form (using AJAX)
A simple contact form that uses AJAX to submit to FormBackend
by formbackend
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.1.2/tailwind.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h1 class="text-xl text-gray-800 font-semibold mb-2">
Simple contact form (with AJAX)
</h1>
<p class="mb-6 text-gray-600 w-2/3 leading-normal">
This form uses AJAX to submit to FormBackend. It replaces the form container with the submission text set on the form in FormBackend - and it adds
one of the values submitted with the form. End result is a green box that says: <span class="bg-indigo-100 px-1">Thank you for your submission, NAME!</span>
</p>. Try submitting it and see! :)
<div id="form-container">
<form accept-charset="UTF-8" action="https://www.formbackend.com/f/2c6c074cd2b9de69" method="POST" id="form-contact">
<div class="mb-3">
<label for="name" class="font-bold uppercase text-gray-600 block tracking-wide text-sm mb-1">Name</label>
<input type="text" id="name" name="name" class="bg-gray-300 rounded p-2 text-gray-600 focus:shadow-outline focus:outline-none" required>
</div>
<div class="mb-3">
<label for="email" class="font-bold uppercase text-gray-600 block tracking-wide text-sm mb-1">Email</label>
<input type="email" id="email" name="email" class="bg-gray-200 rounded p-2 text-gray-600 focus:outline-none" required>
</div>
<div class="mt-4">
<button type="submit" class="bg-blue-700 text-white px-4 py-2 rounded">Submit</button>
</div>
</form>
</div>
CSS
body {
margin: 3rem;
}
JavaScript
$(function() {
var $form = $('#form-contact');
$form.on("submit", function(e) {
var formUrl = $(this).attr('action');
// We don't want the page to submit and refresh
e.preventDefault();
// POST the request to Formbackend (the formUrl value)
$.ajax({
url: formUrl,
type: 'POST',
headers: {
'accept': 'application/json',
},
// We serialize the form fields
data: $form.serialize()
}).done(function(response) {
var successElm = $('<div class="bg-green-100 border border-green-200 text-green-500 p-3">');
successElm.html(`${response.submission_text}, ${response.values.name}!`);
$form.parent().replaceWith(successElm);
}).fail(function() {
// Happens when something goes wrong
}).always(function() {
// This always happens
});
});
});