When I run below code , I always get an empty FormData , is it because of the form too complex ? How should I change the code ?
It seems if I only use tags like form , input , label to construct the form , the FormData object will not get to be empty . Maybe I can manually construct a line and send it via XMLHttpRequest , but have a better way ?
Any help would be appreciate , thank you for your time .
html:
<form enctype="multipart/form-data" id="inquiry" name="inquiry" method="post" role="form"><!--action="processData.php"-->
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label for="name">Your name</label>
<input type="text" class="form-control" id="name" maxlength="100">
</div>
<div class="col-md-6">
<label for="email">Your email address</label>
<input type="text" class="form-control" id="email" maxlength="100">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject" maxlength="100">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label for="message">Your message</label>
<textarea class="form-control" id="message" maxlength="5000"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button id="post-message" type="submit">
<span>Send Message</span>
</button>
</div>
</div>
</form>
js:
'use strict';
var Contact = function() {
var sendData = function() {
var xmlhttp = new XMLHttpRequest() ;
var url = "/php/processData.php";
var inquiryForm = document.forms.namedItem("inquiry");
var FD = new FormData(inquiryForm);
xmlhttp.open("POST", url , true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returnData = xmlhttp.responseText ;
}
};
xmlhttp.send(FD);
for (var [key, value] of FD.entries()) {
console.log(key, value);
}
};
var windowLoadHandler = function() {
window.addEventListener("load",function(){
var inquiryForm = document.getElementById("inquiry");
inquiryForm.addEventListener("submit",function(event){
event.preventDefault();
sendData();
});
});
};
return {
init : function(){
windowLoadHandler();
}
};
}();
sendDatais inside anothe functionnamedItemis not cross-browser, you should be using justthisin the submit handler to catch the form instead. And as noted above, theContactfunction is never executed, and thesendDatafunction is inside it.Contact.init()actually invoked before the page has finished loading?