Using Ajax to submit the form

After clicking the Submit button, all fields will be validated automatically if the SubmitButton plugin is enabled. Usually you have two choices in the case all fields pass their validations:
For the second scenario, you can handle the core.form.valid event as following
FormValidation
.formValidation(
document.getElementById('demoForm'),
{
fields: {
...
},
plugins: {
...
},
}
)
.on('core.form.valid', function() {
// Send the form data to back-end
// You need to grab the form data and create an Ajax request to send them
FormValidation.utils.fetch('/path/to/your/back-end/', {
method: 'POST',
params: {
fieldName: fieldValue,
otherFieldName: otherFieldValue,
...
},
}).then(function(response) {
// Depending on the response from server, you can display a notification
// to let user know if the form is sent successfully
...
});
});
The sample code above uses a built in method FormValidation.utils.fetch(url, options) to send data to given url. It's up to you to choose your favourite library for doing the same thing, such as axios:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
...
<script>
document.addEventListener('DOMContentLoaded', function(e) {
FormValidation
.formValidation(
document.getElementById('demoForm'),
{
...
}
)
.on('core.form.valid', function() {
axios({
method: 'post',
url: '/path/to/your/back-end/',
data: {
fieldName: fieldValue,
otherFieldName: otherFieldValue,
...
},
}).then(function(response) {
...
});
});
});
</script>

Uploading file

You can use the axios library to send file to your back-end as well.
<form id="demoForm" method="POST">
<input type="file" name="avatar" />
...
</form>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
...
<script>
document.addEventListener('DOMContentLoaded', function(e) {
FormValidation
.formValidation(
document.getElementById('demoForm'),
{
...
}
)
.on('core.form.valid', function() {
var formData = new FormData();
// Append the text fields
formData.append('firstName', demoForm.querySelector('[name="firstName"]').value);
formData.append('lastName', demoForm.querySelector('[name="lastName"]').value);
formData.append('username', demoForm.querySelector('[name="username"]').value);
formData.append('email', demoForm.querySelector('[name="email"]').value);
// Append the file
var avatarFiles = demoForm.querySelector('[name="avatar"]').files;
if (avatarFiles.length > 0) {
formData.append('avatar', avatarFiles[0]);
}
axios.post('/path/to/your/back-end/', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function(response) {
...
});
});
});
</script>
The back-end then can get the uploaded file. The following sample code in PHP demonstrates how we can do that:
<?php
$targetFile = __DIR__ . '/uploads/' . basename($_FILES["avatar"]["name"]);
$success = move_uploaded_file($_FILES["avatar"]["tmp_name"], $targetFile);
...

See also