AJAX Installation
If you don't want to redirect your form submitters after a submission or you want to add extra validation logic to your form then submitting with AJAX is a good option. Getform form endpoints accept standard AJAX requests and work cross-origin by default.
Basic AJAX Setup
Paste the example AJAX code below anywhere before the </body>
tag of your HTML.
$("#ajaxForm").submit(function(e){
e.preventDefault();
var action = $(this).attr("action");
$.ajax({
type: "POST",
url: action,
crossDomain: true,
data: new FormData(this),
dataType: "json",
processData: false,
contentType: false,
headers: {
"Accept": "application/json"
}
}).done(function() {
$('.success').addClass('is-active');
}).fail(function() {
alert('An error occurred! Please try again later.')
});
});
Note: If you want to get your responses in JSON format, you need to add dataType: "json"
, it sets Accept Http Header to application/json
Then give "ajaxForm"
ID to your HTML to relate form with your JQuery AJAX Setup.
<form id="ajaxForm" action="https://getform.io/f/{your-endpoint}" method="POST">
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<input type="text" name="message">
<button type="submit">Send</button>
</form>
Uploading Files with AJAX
In order to accept file uploads with AJAX, you simply have to add contentType="multipart/form-data"
to your JQuery code and make sure
that your HTML code includes <input type="file" name="file">
.
$("#ajaxForm").submit(function(e){
e.preventDefault();
var action = $(this).attr("action");
$.ajax({
type: "POST",
url: action,
crossDomain: true,
data: new FormData(this),
dataType: "json",
contentType: "multipart/form-data",
processData: false,
contentType: false,
headers: {
"Accept": "application/json"
}
}).done(function() {
$('.success').addClass('is-active');
}).fail(function() {
alert('An error occurred please try again later.')
});
});