I have a file named feedback.js that I would like to improve.
function feedback(feedbackform) {
// collect the feedbackform data while iterating over the inputs
var data = {};
for (var i = 0; i < feedbackform.length; i++) {
var input = feedbackform[i];
if (input.name && input.value) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(feedbackform.method, feedbackform.action);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
feedbackform.send.disabled = true;
xhr.onloadend = function () {
if (xhr.status == 200) {
feedbackform.send.value = "Sent!";
feedbackform.send.className = "success";
} else {
feedbackform.send.value = "Failed to send";
feedbackform.send.className = "fail";
}
};
return false;
}
- Is there a modern way to collect form inputs? E.g. json enctype?
- Is disabling the submit button a good idea to prevent multiple form submissions?
- If the form fails to send, what's a good recourse (to prevent data loss of the filled form) I can give the user? Perhaps munge it into a
mailto:
command?
Are there any other tweaks I can make without relying on any dependencies, such as trying to reduce code size?