Here i am trying to submit form using post method via ajax.I used formData object to colleect and send the form.But when i echo a field value from destination page it returns an empty string.Is that means the form is not submitting.In console i receive a status code of 200.and formdata object also gets all the input.What might be the reason ?
<form action='home.php' method='POST' id='myform' enctype='multipart/form-data'>
name : <input type='text' name='myname' id='name_select'>
file : <input type='file' name='myfile' id='file_select' >
<input type='submit' value='form submit' id='submitbtn'>
</form>
<script>
var name=document.getElementById('name_select');
var file=document.getElementById('file_select');
var sub=document.getElementById('submitbtn');
var form=document.getElementById('myform');
sub.addEventListener('click',function(event){
event.preventDefault();
sub.value='uploading...';
var xhr=new XMLHttpRequest();
var formdata=new FormData();
var files=file.files[0];
var inputs=document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++){
if(!inputs[i].disabled){
if(inputs[i].type=='file'){
formdata.append(inputs[i].name,files,files.name);
}else{
formdata.append(inputs[i].name,inputs[i].value);
}
}
}
xhr.onreadystatechange=function (){
if(xhr.readyState==4){
if(xhr.status==200){
console.log('form submitted');
alert((xhr.response));
sub.value='upload';
}else{
console.log('there is a problem');
}
}
}
xhr.open('POST','home.php',true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(formdata);
});
</script>
home.php:
<?php
echo $_POST['myname'];
?>