0

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'];

?>
AL-zami
  • 8,902
  • 15
  • 71
  • 130

2 Answers2

0

This might happen in multipart form data. Generally you can simplify ajax using jquery form plugin. http://malsup.com/jquery/form/

$('#myForm').ajaxForm();

This plugin is based on jquery ajax and mostly support everything in jquery ajax (beforeSend, success, fail, ...).

eeXBee
  • 133
  • 7
0

this so post solved my problem. the problem lies in the following line

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

as i have binary data to send to server so i have multipart/form-data as enctype in form elemet.application/x-www-form-urlencoded is used to send a query string to the server.On the other hand multipart/form-data is used to send large binary data to server.So ,omitting the above stated line solved my problem.

Community
  • 1
  • 1
AL-zami
  • 8,902
  • 15
  • 71
  • 130