0

I am trying to upload file with ajax it does not work for some reason, can you see what's up?

     function upload(myform)

     var file = this.files[0];
     var formData = new FormData();
     formData.append("material_file", document.getElementById("myfile"));

    xmlhttp = new XMLHttpRequest();
    xmlhttp.addEventListener('progress', function(e) {
        var done = e.position || e.loaded, total = e.totalSize || e.total;
        console.log('xmlhttp progress: ' + (Math.floor(done/total*1000)/10) + '%');
    }, false);
    if ( xmlhttp.upload ) {
        xmlhttp.upload.onprogress = function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xmlhttp.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
        };
    }
    xmlhttp.onreadystatechange = function(e) {
        if ( 4 == this.readyState ) {
            console.log(['xmlhttp upload complete', e]);
        }
    };
    xmlhttp.open('post', process_pdf.php, true);
    xmlhttp.setRequestHeader("Content-Type","multipart/form-data");
    xmlhttp.send(formData);
     }


<form onsubmit="upload(this)">
     <input type="file" name="myfile">
</form>

When I browse to the file and click submit I get error

John Smith
  • 681
  • 5
  • 13
  • 30

1 Answers1

0

According to the error, you need to create a myForm variable before you use it.

However, your larger problem is that one can't upload files with AJAX alone. Try using a library like SWFupload.

If you don't want to use Flash or another plugin, you'll need to skip the AJAX and work straight with POST.

<form method="post" enctype="multipart/form-data" action="/PATH/TO FILE">
    <input type="file" name="myfile">
    <input type="submit" value="upload file">
</form>
Community
  • 1
  • 1
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • SWFupload *is* a non-jQuery solution, jQuery's just one way to implement it. – SomeKittens Oct 18 '12 at 22:22
  • I dont want to use flash either thanks. It requires extra plugin and open file window always focus behind browser. – John Smith Oct 18 '12 at 22:25
  • 1
    XMLHttpRequest isn't capable of sending upload data. If you don't want to use SWFUpload, your other option is *XMLHttpRequest2*, which is supported by most modern browsers: http://www.html5rocks.com/en/tutorials/file/xhr2/ - http://caniuse.com/xhr2 – Matt Stone Oct 18 '12 at 22:33
  • @SomeKittens The `append` method refers to the `FormData` object - https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData – Ian Oct 18 '12 at 22:35