I am creating an AJAX PHP upload script, but I am having troubles. After the user selects an image to upload, it will show in the div container that I specified in the javascript file (good). But, the moving the uploaded file does not seem to work, or at least I think that is what the problem is. I set the uploads/ folder to have permission of "777".
Here is the JS file:
$(document).ready(function () {
$("#upload-image-button").hide();
var input = document.getElementById("images"),
formdata = false;
function showUploadedItem(source) {
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img");
img.src = source;
$("#topic-img-container").html(img);
}
if (window.FormData) {
formdata = new FormData();
$("#upload-image-button").hide();
}
$("input[type='file']").live("change", function(event) {
$("#response").html("Uploading...");
var i = 0, len = this.files.length, img, reader, file;
for (; i < len; i++) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("images[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "db/upload_image.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
}, false);
});
Here is the PHP file:
<?php
foreach($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
print_r($_FILES);
$name = $_FILES["images"]["name"][$key];
move_uploaded_file($FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES["images"]["name"][$key]);
echo $FILES["images"]["tmp_name"][$key];
}
}
echo "Success";
?>
It gets into the loop when there is no error. When I go to the upload folder, there are no new files. Any idea why this might be?
You cannot upload files using AJAX. You need a helper Iframe that you send via a regular form-post.