I have a really simple HTML page with an image upload form as follows:
<form id="file_data">
<input type='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>
</form>
My Javascript:
$(document).ready(function() {
$("form[id='file_data']").submit(function() {
var form_data = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: form_data,
processData: false,
success: function(data) {
alert(data);
}
});
});
});
upload.php is creating a directory to store images, if the directory does not already exists. Then is supposed to store image in the directory:
<?php
define("IMAGE_DIRECTORY", "images");
//If the directory for images does not exist, create it
if(!is_dir(IMAGE_DIRECTORY)) {
mkdir(IMAGE_DIRECTORY, 0777, true);
}
move_uploaded_file($_FILES["tmp_name"], IMAGE_DIRECTORY . "\\" .basename($_FILES["file"]["name"]));
?>
While the PHP script will create the directory, if it does not already exist, it is not saving any images to the directory. I'm assuming I am not accessing the image correctly from PHP, but the tutorials I've looked at don't explain too much of the details of what is actually going on when an image is sent in an Ajax call to PHP.
Problem you are missing in code:
Html: enctype="multipart/form-data" on form to upload file, also <input type="file" missing name="file"
Php: move_uploaded_file is not correct you are missing ['file'] for tmp_name $_FILES['file']["tmp_name"]
Ajax: dataType:"html" is missing so that your ajax get response as string from server
Update your Html, Php and Ajax code like this:
Html Code:
<form id="file_data" enctype="multipart/form-data" method="post">
<input type='file' name='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>
</form>
Php Code:
<?php
define("IMAGE_DIRECTORY", "images");
//If the directory for images does not exist, create it
if(!is_dir(IMAGE_DIRECTORY)) {
mkdir(IMAGE_DIRECTORY, 0777, true);
}
move_uploaded_file($_FILES['file']["tmp_name"], IMAGE_DIRECTORY . "\\" .basename($_FILES["file"]["name"]));
?>
Ajax Code:
$.ajax({
url: "upload.php",
data : form_data,
type : "POST",
async: false,
cache: false,
contentType: false,
processData: false,
dateType : "html",
success: function(data) {
alert(data);
}
});