I don't have much experience with ajax but seeing an issue when sending form data to a ASP controller.
Scenario 1
Set data
in ajax request to
$(this).serialize()
All form data is posted to the conrtroller without any page redirect, but excludes any files sent with the form.
Scenario 2
set data
in ajax request to
formdata
All form data is posted, including uploaded files, but the page refreshes, which I do not want to happen.
What is going on here, and how can I send the files without refreshing the page?
Code
// Clear any previous 'success' messages (in case of error)
$('form .btn').on('click', function () {
$('#result').html('');
});
// Submit form
$('form').submit(function () {
// Build form data
var formdata = new FormData();
var fileInput = document.getElementById('fileInput');
for (i = 0; i < fileInput.files.length; i++) {
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
// Send ajax request
$.ajax({
url: this.action,
type: this.method,
data: formdata, // fails to send files when set to $(this).serialize()
beforeSend: function () {
$('form .btn').prop('disabled', true);
},
success: function (result) {
$('form .btn').prop('disabled', false)
$('form .form-control').val('');
$('#result').html('Thank you. We will contact you shortly.');
$('.validation-summary-errors ul li').css('display', 'none');
},
error: function (result) {
$('form .btn').prop('disabled', false)
alert('An error occurred on the server. Please try again. \n\n If this keep happening, please email us at office@auroraglobal.ru');
}
});
return false;
});