user1775888
user1775888

Reputation: 3303

upload file through ajax

I use 2 file index.js, upload.php try to upload file(img) through ajax and if success append to div uploadfile_show.
but it doesn't work , have few question and below is my code any suggestion?

Thanks.

upload.php
1. form enctype still need to add?
2. if($_FILES) and check $_FILES size or tmp_name still use $_FILES?

if($_FILES){
    $filename = $_FILES['uploadfile']['name'];
    $filetmp = $_FILES['uploadfile']['tmp_name'];
    $filesize = $_FILES['uploadfile']['size'];
    if($filesize < 1000000){
        move_uploaded_file($filetmp,'upload/tmp/'.$filename);
        print"
            upload success
            <img src=\"upload/tmp/$filename\">
        ";
    }
    else{
    }
}
else{
    print"
        <div class=\"uploaddiv\">
            <form enctype=\"multipart/form_data\">
                <input type=\"type\" name=\"uploadfile\">
                <input type=\"submit\" value=\"upload\" class=\"btn\">
            </form>
        </div>
    ";
}
print"
    <div class=\"uploadfile_show\"></div>
";

index.js
3. this few line is it the right?
var uf = $('.uploaddiv form');var fd = new FormData(uf);fd.append('uploadfile', uploadfile);
data: fd,
4. any thing I missed or wrong?

$('.btn').click(function(){
    var uf = $('.uploaddiv form');
    var fd = new FormData(uf);
    fd.append('uploadfile', uploadfile);
    $.ajax({
        type: "POST",
        url: "upload.php",
        data: fd,
        processData:false,
        contentType: false,
        success: function(html){
            $('.uploadfile_show').append(html);
        }
    });
});

Upvotes: 2

Views: 3372

Answers (1)

Musa
Musa

Reputation: 97672

FormData takes a form element in its constructor not a jQuery object, also as you are using ajax to submit the form you'll have to prevent its default action(i.e. submitting) by calling preventDefault()

$('.btn').click(function(e){
    e.preventDefault();
    var uf = $('.uploaddiv form');
    var fd = new FormData(uf[0]);
    $.ajax({
        type: "POST",
        url: "upload.php",
        data: fd,
        processData:false,
        contentType: false,
        success: function(html){
            $('.uploadfile_show').append(html);
        }
    });
});

Upvotes: 2

Related Questions