JQuery AJAX sending files array from form

ajax-formsfile uploadjquery

I got this code somewhere to upload pics without refreshing the browser. However I didn't like the uploader file so I decided to use the old one I used to work with. The problem is that it is sending an array instead of a string from the javascript file (it was intended to be sent multiple files instead of only one). Here is the code that makes the array:

input.addEventListener("change", function (evt) {
    document.getElementById("response").innerHTML = "Loading . . ."

    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];
            if (formdata) {
                formdata.append("uploaded_file[]", file);
    }   }   }

    if (formdata) {
        $.ajax({
            url: "img_upload.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false
        }).done(function (res) {
                            /* *** show uploaded item *** */
                            /* *** show response *** */
            });
    }

My knowledge in Javascript is really weak and I can't find out how to modify this code to send the uploaded file by itself instead of an array.

I tried these independently, but none of them worked (send_img is the form name/id):

formdata = document.send_img.uploaded_file.value;
formdata = document.getElementById("uploaded_file");
formdata = new formdata ($('#send_img'));
formData = $('#send_img').serialize();
formdata.replaceWith("uploaded_file[]", file);

I also tried eliminating the for to use the same key (0) but it doesn't work that way.
The condensed code for img_upload.php is:

$fileName = $target . $_FILES["uploaded_file"]["name"];
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];
$fileName = $new_name .  "."  . $fileExt;
move_uploaded_file($fileTmpLoc, "images/images/temp/$fileName");

How can I send the uploaded file (or header or whatever it is supposed to send) in just one string and, in case of a second file being added, replace the first one instead of creating a second value in the array?

Best Answer

The problem is not your logic, the problem is that files cannot be uploaded via ajax.

But maybe you will ask, how did others do? Well, try a form plugin (another .js that works with jQuery)

I found this for you, it works using 'submit' method but maybe you can do a submit when input change or find other kind of solution with javascript actions.

Check this: http://www.miguelmanchego.com/2009/subir-archivos-usando-ajax-jquery/

Website is in Spanish but translate it to English if you need. Also that link includes a live example and source-code download.

Regards.