PHP Ajax Parameter on Upload not set?

- 1 answer

Ad

I try to do a simple simple upload but i guess iam too dumb or its too late here.

I searched a bit and founded this here on Stack

HTML

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input id="uploadBTN" type="button" value="Stash the file!"></input>
<div id="output"></div>

JS

$("#uploadBTN").click(function(event) {

        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: './ajax/upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });

    });

PHP

if(isset($_POST['file'])){
    $filename = $_FILES['file']['name'];
    if(isset($filename) && !empty($filename)){
        echo 'sup my man?!';
    }else{
        echo 'please choose a file';
    }
}else{
    echo 'not set';
}

The Problem with these Stuff is its saying not set so? With GET Method its same cause i tested mostly everthing out. And no i dont want to use any plugin or something else :)

My Question is how can i access correctly the File ? Or if this Lines of Code are totally Crap what is a other solve?

Thanks!

Ad

Answer

Ad

Try this, It works for me.

$("#uploadBTN").click(function(event) {
    event.preventDefault();
    var tmp_form = $("#fileinfo")[0];
    var fd = new FormData(tmp_form);
    $.ajax({
        url: './ajax/upload.php',  
        type: 'POST',
        data: fd,
        async: true,
        success:function(data){
            $('#output').html(data);
        },
        cache: false,
        contentType: false,
        processData: false
    });

});



<form action="" method="post" enctype="multipart/form-data"  id="fileinfo">
        <input type="file" name="file" required >    
</form>

<input id="uploadBTN" type="button" value="Stash the file!"></input>
<div id="output"></div>


if(isset($_FILES['file'])){
    $filename = $_FILES['file']['name'];
    if(isset($_FILES['file']['name']) && !empty($filename)){
        echo 'sup my man?!';
    }else{
        echo 'please choose a file';
    }
}else{
    echo 'not set';
}
Ad
source: stackoverflow.com
Ad