0

I've looked at several answers here and they all use jQuery's .ajax() method. Below I have a vanilla JS method that is a trimmed down version which I am using with some success.

       function ajax(options){
            var settings = {
                method : 'POST',
                url : 'endpoint.php',
                data : null,
                done : function(){},
                fail : function(){},
                complete : function(){}
            };

            if(options) for(option in options) settings[option] = options[option];

            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function(){
                if (xhttp.readyState == 4){
                    if(xhttp.status == 200){
                        settings.done(xhttp.responseText);
                    } else {
                        settings.fail(xhttp.responseText);
                    };
                    settings.complete(xhttp.responseText);
                };
            };
            xhttp.open(settings.method, settings.url, true);
            xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            xhttp.send(settings.data);
        };

Next is the function that assigns the file to a new FormData() object.

        function beginUpload(index){
            var file = files.files[index];
            var pkg = new FormData();
            pkg.append('file', file);
            pkg.append('size', file.size);
            ajax({
                data : pkg,
                done : function(res){
                    console.log(res);
                }
            });
        };

Now, here's the problem: All tutorials and examples I've found say that the file will be found in the $_FILES global variable after the request is completed. I get a 200 response doing a var_dump() and $_FILES for me is empty but $_POST is not. $_POST has what looks like the file inside of it. Checked all the php.ini settings from this question.

Community
  • 1
  • 1
Donnie D'Amato
  • 3,832
  • 1
  • 15
  • 40

1 Answers1

1
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

Don't set that. XHR will recognise the FormData object and set it to the correct value (which that is not).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335