0

Im trying to upload a file using ajax posting to an object oriented class, but it isn't posting correctly.

Here is the ajax

 var handleUpload = function(event)
 {


event.preventDefault();
event.stopPropagation();

var fileInput = document.getElementById('file');

var data = new FormData();

for(var i = 0; i < fileInput.files.length; i++)
{

    data.append('file[]', fileInput.files[i]);

}

var request = new XMLHttpRequest();

request.upload.addEventListener('progress', function(event)
{


});

request.upload.addEventListener('load', function(event)
{


});

request.upload.addEventListener('error', function(event)
{


});

request.open('POST', 'profile.php');
request.setRequestHeader('Cache-Control', 'no-cache');
request.send(data);

   }

   window.addEventListener('load', function(event)
   {

var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);

   });

This is the php code that is calling the function in the class i created. The javascript successfully posts, however the $_FILES array isn't set so the php if statement isn't running.

if(!empty($_FILES['file']) && isset($_POST['special']))
{
    $special = $_POST['special'];
    $date = $_POST['date'];
    $user->postSpecial($special, $date, $_FILES);

}
user2872510
  • 115
  • 1
  • 1
  • 10

2 Answers2

1

Post your form to a hidden iframe

As described by @nietonfir you can't just post a form with input=file using XMLHTTPRequest. However, one workaround that is common when XHR2 isn't available (or you don't want to use it) is to post your form to a hidden iframe on the page. There are many JavaScript libraries/jQuery plugins, etc. that provide an abstraction for this (see https://github.com/Widen/fine-uploader for but one example), but the concept is fairly simple.

rodrigo-silveira
  • 12,607
  • 11
  • 69
  • 123
0

Your AJAX call fails because you can't submit files asynchronously*. And that's why $_FILES is empty. What you can (and should) do is resort to the so called iframe form post hack (or switch to jquery and the jquery file upload plugin).

* This is adressed in XMLHttpRequest2. See http://caniuse.com/#feat=xhr2 for browser support.

nietonfir
  • 4,797
  • 6
  • 31
  • 43
  • it is possible I've seen it done – user2872510 Dec 29 '13 at 22:09
  • Oh please, of course it's possible as I've already described. But not with pure XMLHTTPRequest. Google it for yourself if you don't believe me or use the SO search: http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload, http://stackoverflow.com/questions/2751795/ajax-file-upload – nietonfir Dec 29 '13 at 22:12