Here is the code which allows you to submit the form to the webflow server using Ajax(as a native webflow form) but allows you to define your Success and Error scenarios(Instead of the default success and error block).
function makeWebflowFormAjax( form, successCallback, errorCallback, whileSubmitingForm) {
let siteId = $('html').attr('data-wf-site');
let formUrl = "https://webflow.com" + '/api/v1/form/' + siteId;
var payload = {
name: form.attr('data-name'),
source: window.location.href,
test: Webflow.env(),
fields: {},
fileUploads: {},
dolphin: /pass[\s-_]?(word|code)|secret|login|credentials/i.test(form.html()),
};
findFields(form, payload.fields)
whileSubmitingForm()
// call via ajax
$.ajax({
url: formUrl,
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true,
success: function (resultData) {
if (typeof successCallback === 'function') {
successCallback(resultData);
}
},
error: function (e) {
// call custom callback
if (typeof errorCallback === 'function') {
errorCallback(e)
}
}
});
}
function findFields(form, result) {
result = result || {};
form.find(':input:not([type="submit"]):not([type="file"])').each(function (i, el) {
var field = $(el);
var type = field.attr('type');
var name = field.attr('data-name') || field.attr('name') || 'Field ' + (i + 1);
var value = field.val();
if (type === 'checkbox') {
value = field.is(':checked');
} else if (type === 'radio') {
if (result[name] === null || typeof result[name] === 'string') {
return;
}
value = form.find('input[name="' + field.attr('name') + '"]:checked').val() || null;
}
if (typeof value === 'string') {
value = $.trim(value);
}
result[name] = value;
});
}
function validateForm(form){
if (form[0].checkValidity()){
// A valid form ready for submit
makeWebflowFormAjax(form, successCallback, errorCallback, whileSubmitingForm)
}
else{
form[0].reportValidity()
}
}
function successCallback(resultData){
// Define here What should happen after successful Form Submission
alert('Heyy, Successfully submit the form using Ajax to webflow Server')
}
function errorCallback(e){
// Define here What should happen after Failure of Form Submission
alert('Something went wrong while submitting the form using Ajax to webflow Server')
}
function whileSubmitingForm(){
// Define here What should happen while submitting the form data and waiting for the response
$('#mirror-submit-btn').text('Please wait..')
}
$('#mirror-submit-btn').click(function(){
let form = $('#from-id')
validateForm(form)
})
You need to have normal button
or link block, not the submit
button inside the form.
Note: This does not handle the file upload, so if you are submitting file with your form this might not work.