Reputation: 592
i think i sleep already, cant find my mistake. Thanks for your advance for this short post and for your help.
My Javascript
$("#avatarImage").change(function() {
$("#avatar").html('<img src="assets/images/loader.gif" alt="">');
$.post( 'ajax/avatarUpload.php', function( data ) {
alert(data);
});
});
My Form
<form enctype="multipart/form-data" method="post" action="ajax/avatarUpload.php" id="avatarUpload">
<span class="btn btn-teal btn-file btn-sm"><span class="fileupload-new"><i class="fa fa-pencil"></i></span><span class="fileupload-exists"><i class="fa fa-pencil"></i></span>
<input type="file" name="avatar" id="avatarImage">
</span>
</form>
My PHP Code
$file_up_size = $_FILES['avatar']['size'];
$file_name = md5(uniqid(rand(), true));
$add = '../assets/images/avatars/' . $file_name;
if(!move_uploaded_file($_FILES['avatar']['tmp_name'], $add)){
echo 'FEHLER';
} else {
//database crap
}
My Error(s)
Notice: Undefined index: avatar in ...
Thanks for your help, i am blind this evening.
Upvotes: 0
Views: 102
Reputation: 50787
Your $.post()
is posting to the form but it is not supplying any data to that form. This is causing undefined index: avatar
because your post
doesn't include an index of avatar
within the files
array. To resolve this, pass along the image in your POST
by constructing a FormData
object. Further, the ajax wrapper $.post()
doesn't allow you to set certain options, and therefore we need to unwrap it and use $.ajax()
instead.
$("#avatarImage").change(function() {
$("#avatar").html('<img src="assets/images/loader.gif" alt="">');
var fd = new FormData()
fd.append('avatar', $('#avatarImage')[0].files[0]);
$.ajax({
url: 'ajax/avatarUpload.php',
type: 'POST',
data: fd,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
});
Upvotes: 3