Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
        }
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
238 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...