0

I know not working is a vague problem-description. In console I see the error:

TypeError: $(...).files is undefined

Here is the jQuery code used to send the Ajax request:

$(document).ready(function(){
    $("input[type=submit]").click(function(e){
    e.preventDefault();
    e.stopPropagation();
    $.ajax({
        url : "",
        type : "POST",
        data : $('input[type=file]').files[0],
        success : function(){
            console.log("Successfully done!");
            },
    });

});
});

Here is the HTML:

<form method="POST" enctype="multipart/form-data">
<label >Please Select a File to Upload</label><br />
<input type="file" name="name" /><br /><br />
<input type="submit" value="Upload" name="upload" />
</form>

and Here is the PHP to process to upload the file:

session_start();
if(isset($_POST['upload']))
{
    print_r($_FILES);
    move_uploaded_file( $_FILES['name']['tmp_name'] , 'up/'.$_FILES['name']['name'] );
    echo "File uploaded Successfully";
    echo "<br />" . "<br />";
}

All the above code simply are in a single page.

  • possible duplicate of [How can I upload files asynchronously with jQuery?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) – putvande Feb 10 '14 at 11:30

1 Answers1

0

Try this, because AJAX submit by default files in string

$("form").submit(function(e) {
    e.preventDefault();
    var fd = new FormData($("form")[0]);
    $.ajax({type: 'POST',
        url: "",
        data: fd,
        processData: false,
        contentType: false,
        success: function() {
            // if success
        }
    });
    return false;
});

And this

if(is_uploaded_file($_FILES['name']['tmp_name'])){
    move_uploaded_file( $_FILES['name']['tmp_name'] , 'up/'.$_FILES['name']['name'] );
    echo "File uploaded Successfully";
    echo "<br />" . "<br />";
}
  • I face an error: `TypeError: 'append' called on an object that does not implement interface FormDat..` –  Feb 10 '14 at 11:42
  • Get you an URL with GET vars on browser? –  Feb 10 '14 at 12:00
  • Hmm, I'm trying the code with my form and it works, the diference is that I append form to div when open form and call it on submit like $("body").on("submit","form",function(e)... instead of use document ready –  Feb 10 '14 at 12:17
  • No the problem seems to be with the form structure itself. –  Feb 10 '14 at 12:23