5

I'm trying to use FormData to send data via AJAX to a PHP script. There doesn't seem to be any problem with the input type text values but when i try to append files i get the error TypeError: Value does not implement interface FormData.

I am new to FormData, but i searched on the web and couldn't find any doc on this error.

Here's the form :

<form id="item_form" class="item_form" enctype="multipart/form-data">
    <div class="">
        <label for="emp_photos">photos</label>
        <input id="emp_photos" class="inputText" type="file" value="" name="emp_photos">
    </div>
</form>

here'S the Javascript :

var formData = new FormData();      
formData.append('photos', $('#emp_photos').files[0]);

here's the error i get in firebug :

TypeError: Value does not implement interface FormData. 

...igger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},...

jquery....min.js (line 5)

What am i doing wrong here ?

EDIT: ajax part

$.ajax({
   type: 'POST',
   url: '"; 
   echo $_SESSION["url_base"];
   echo "operations/add_employes',
   data: formData,
   xhr: function() {  // custom xhr
      myXhr = $.ajaxSettings.xhr();
      if(myXhr.upload) { // check if upload property exists
         myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
      }
      return myXhr;
   },
   success: function(msg) {/*...*/}

});
3
  • 1
    Where is your ajax call. Can we see that? Commented May 2, 2013 at 20:06
  • This seems to be a proper solution stackoverflow.com/questions/15259632/… Commented May 2, 2013 at 20:17
  • Ty Tim that helped me solve it :) Commented May 2, 2013 at 20:37

1 Answer 1

2
var inputs = $("input[type=file]"),
    files = [];

// jquery or javascript have a slightly different notation
// it's either accessing functions () or arrays [] depending on which object you're holding at the moment
for (var i = 0; i < inputs.length; i++){
    files.push(inputs.eq(i).prop("files")[0]);
    //files.push(inputs[i].files[0]);
    //filename = inputs[i].files[0].name;
    //filesize = inputs[i].files[0].size;
}

if (formdata) {
    // you can use the array notation of your input's `name` attribute here
    formdata.append("emp_photos[]", files);
}
Sign up to request clarification or add additional context in comments.

5 Comments

thnx a lot , its great
how will "emp_photos[]" will be accessed in php backend
$_POST['emp_photos'] foreach ($_POST['emp_photos'] as $i => $value) { echo "emp_photos[$i] is $value<br />"; }
shouldn't it be $_FILES
that could work yes. sorry my php is not up-to-date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.