JQuery upload

Ive been struggeling to upload a file by jQuery. I want to upload the file sepretly (without having to enclose it in a form or iFrame).

So, Ive constructed the following:-
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        $(document).on("click","#btnUpload", function(e) {
            var fileSelect = $("#tstFile");
            var files = fileSelect.files;

            var frmData = new FormData();

            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                frmData.append('tstFile[]', file, file.name);
            }

            $.ajax({
                url: 'upload.php',
                type: 'POST',
                data: frrmData,
                cache: false,
                contentType: false,
                processData: false,
                success:function(data){
                    alert(data);
                },
            });
        });
    });
</script>

    <input type="file" id="tstFile" name="tstFile" />
    <button id="btnUpload">Upload</button>

Open in new window


On the debugger I get "files not found", and nothing uploaded on my upload.php page into the $_FILES object.

Any ideas how to fix this?
tonelm54Asked:
Who is Participating?
 
hieloCommented:
>> var files = fileSelect.files;
files is a property of <input type="file">.  That means that for the above line to work as expected, fileSelect needs to be a reference to some <input type="file"> node.  Unfortunately, fileSelect is NOT a reference to an <input type="file"> node.

>> var fileSelect = $("#tstFile");
The jquery $() function returns a jquery object.  What you actually need is the DOM node that #tstFile refers to, not the jquery object.  So, call the get() method on your jquery object:

var fileSelect = $("#tstFile").get(0);

and be sure to fix the typo pointed out by Chris Stanyon.
data: frmData

>> frmData.append('tstFile[]', file, file.name);
Are you trying to allow multiple files at once? If so add the "multiple" attribute to your <input> tag as well.
0
 
Chris StanyonCommented:
If that's a copy/paste of your code, then you have a typo:

data: frrmData,

should be:

data: frmData
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.