Reputation: 693
I am trying to do an image file upload with ajax without refreshing the page but the file won't be moved to the specified folder i did very basic file upload php code to avoid errors and develop it later
if($_SERVER["REQUEST_METHOD"]=="POST"){
$file = $_FILES["uploaded"]
$target_dir = "user_image/";
$target_file = $target_dir . basename($_FILES["uploaded"]["name"]);
move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target_file);
}
My ajax and JavaScript are working fine but there is no image on the target file user_image/
<script charset="UTF-8">
function _(id){
return document.getElementById(id);
}
_("file_upload").onchange = function() {
//_("file_upload").submit();
var id = _("user_id").innerHTML;
var file = _("file_upload").files[0];
var formdata = new FormData();
formdata.append("file1",file);
var ajax = new XMLHttpRequest();
ajax.onreadystatechange =
function(){
if(ajax.readyState==4 && ajax.status==200){
_("one").remove();
var img = document.createElement('img');
var first_path = '/user_image/';
var path = first_path.concat(id,'.png');
img.setAttribute('alt','User image');
img.setAttribute('id','one');
img.setAttribute('src',path);
_("user").appendChild(img);
alert("end");
}
else{
_("one").remove();
var img = document.createElement('img');
img.setAttribute('src','/img/loading.gif');
img.setAttribute('alt','User image');
img.setAttribute('id','one');
_("user").appendChild(img);
}
}
ajax.open("POST","upload_image.php");
ajax.send(formdata);
};
</script>
Upvotes: 0
Views: 127
Reputation: 13304
You need to change the request header to make this work.
ajax.setRequestHeader("Content-type", "multipart/form-data");
Upvotes: 2