I want to submit a form that has some field such as firstName, LastName, Message, Email and a file attachment by Ajax.
There is a Cancel button in the form that make cancel the uploading file but just cancelling upload! In other words, if user click on the submit button after cancelling, the form must submit but without the attachment file. Or user can select another file and then submit.
My code has two problems:
How can I solve these problems (Preferably without the use of JQuery)?
Please help me.
Javascript code:
var ContactForm = {
xhr: new XMLHttpRequest(),
aborted: false,
form: document.querySelector("#contact-form"),
attachment: document.querySelector("#Attachment"),
progressArea: document.querySelector("#progress-area")
};
var myContactForm = ContactForm;
$(document).ready(function () {
if (myContactForm.attachment) {
myContactForm.form.addEventListener("submit",
function (submitEvent) {
submitEvent.preventDefault();
//myContactForm = Object.create(ContactForm);
const files = myContactForm.attachment.files;
//const xhr = new XMLHttpRequest();
myContactForm.xhr.open("POST", "/ContactUs/ContactUsForm/");
const formData = new FormData(myContactForm.form);
myContactForm.xhr.addEventListener("load",
function () {
console.log(myContactForm.xhr.responseText);
});
const block = addProgressBlock(files[0]);
myContactForm.xhr.upload.addEventListener("progress",
function (event) {
const progressDiv = block.querySelector(".progress-bar div");
const progressSpan = block.querySelector("span");
//progress.innerHTML = "progress" + event.loaded + " bytes sent.<br />";
if (event.lengthComputable) {
const percent = ((event.loaded / event.total) * 100).toFixed(1);
progressSpan.innerHTML = percent + "%";
progressDiv.style.width = percent + "%";
//let percent = parseInt((event.loaded / event.total) * 100);
//progress.innerHTML += "progress: " + percent + "% sent.";
}
});
myContactForm.xhr.addEventListener("abort", function () {
myContactForm.xhr.onreadystatechange = null;
myContactForm.aborted = true;
myContactForm.attachment.files = null;
myContactForm.progressArea.innerHTML = null;
});
if (myContactForm.aborted) {
myContactForm.xhr = null;
myContactForm = null;
myContactForm = Object.create(ContactForm);
return false;
}
myContactForm.xhr.send(formData);
});
}
var cancelUpload = document.querySelector("#cancelUpload");
cancelUpload.addEventListener("click", function () {
myContactForm.xhr.abort();
});
});
function addProgressBlock(file) {
const html = `<label>file: ${file.name}</label>
<div class="progress-bar">
<div class="progress-bar progress-bar-striped active" style="width: 0%;"></div>
<span>0%</span>
</div>`;
const block = document.createElement("div");
block.setAttribute("class", "progress-block");
block.innerHTML = html;
myContactForm.progressArea.appendChild(block);
return block;
}
HTML file:
<form id="contact-form" asp-controller="ContactUs" asp-action="ContactUsForm" enctype="multipart/form-data" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input asp-for="@Model.FirstName" type="text" name="FirstName" maxlength="25" required class="form-control" placeholder="Please enter your firstname">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div id="upload-area">
<label id="btnUploadAttachment" asp-for="@Model.Attachment" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i>Upload file
</label>
<input asp-for="@Model.Attachment" name="Attachment"
type="file"
class="form-control" />
<button id="cancelUpload">cancel</button>
</div>
<div id="progress-area">
</div>
</div>
</div>
<div class="col-md-12">
<input id="submitContactForm" type="submit" class="btn btn-success btn-send" value="Sendmessage">
</div>
</form>
Cancel button in form:
<button id="cancelUpload" type="button">cancel</button>
JavaScript Code:
var ContactForm = {
xhr: new XMLHttpRequest(),
aborted: false,
form: document.querySelector("#contact-form"),
attachment: document.querySelector("#Attachment"),
progressArea: document.querySelector("#progress-area")
};
var myContactForm = Object.create(ContactForm);
$(document).ready(function () {
if (myContactForm.attachment) {
myContactForm.form.addEventListener("submit",
function (submitEvent) {
submitEvent.preventDefault();
//myContactForm = Object.create(ContactForm);
const files = myContactForm.attachment.files;
//const xhr = new XMLHttpRequest();
myContactForm.xhr.open("POST", "/ContactUs/ContactUsForm/");
const formData = new FormData(myContactForm.form);
myContactForm.xhr.addEventListener("load",
function () {
if ((myContactForm.xhr.status >= 200 && myContactForm.xhr.status < 300) || myContactForm.xhr.status === 304) {
var result = JSON.parse(myContactForm.xhr.responseText);
var messageAlert = 'alert-' + result.type;
var messageText = result.message;
var alertBox = '<div class="alert ' +
messageAlert +
' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
messageText +
'</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
console.log(myContactForm.xhr.responseText);
} else {
console.log("Status: " + myContactForm.xhr.status);
}
});
const block = addProgressBlock(files[0]);
myContactForm.xhr.upload.addEventListener("progress",
function (event) {
if (block != null) {
const progressDiv = block.querySelector(".progress-bar div");
const progressSpan = block.querySelector("span");
//progress.innerHTML = "progress" + event.loaded + " bytes sent.<br />";
if (event.lengthComputable) {
const percent = ((event.loaded / event.total) * 100).toFixed(1);
progressSpan.innerHTML = percent + "%";
progressDiv.style.width = percent + "%";
//let percent = parseInt((event.loaded / event.total) * 100);
//progress.innerHTML += "progress: " + percent + "% sent.";
}
}
});
myContactForm.xhr.addEventListener("abort", function () {
myContactForm.xhr.onreadystatechange = null;
myContactForm.attachment.files = null;
myContactForm.attachment = null;
myContactForm.progressArea.innerHTML = null;
myContactForm.aborted = false;
myContactForm.xhr = null;
document.querySelector("#Attachment").value = null;
myContactForm = Object.create(ContactForm);
return false;
});
myContactForm.xhr.send(formData);
});
}
var cancelUpload = document.querySelector("#cancelUpload");
cancelUpload.addEventListener("click", function () {
myContactForm.xhr.abort();
});
});
function addProgressBlock(file) {
if (file != null) {
const html = `<label>file: ${file.name}</label>
<div class="progress-bar">
<div class="progress-bar progress-bar-striped active" style="width: 0%;"></div>
<span>0%</span>
</div>`;
const block = document.createElement("div");
block.setAttribute("class", "progress-block");
block.innerHTML = html;
myContactForm.progressArea.appendChild(block);
return block;
}
return null;
}