I am facing an error where I am unable to pass the image file through AJAX when uploading a image file. Here are my codes
AJAX
var file = $("#thumbnail").get(0).files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file", file);
alert (formdata);
$.ajax({
url: "php/post-check.php",
type: "POST",
data: {
title: title,
thumbnail: formdata
},
success: function (data) {
$("div#postresult").removeClass("alert alert-danger");
$("div#postresult").html(data);
}
});
PHP
<?php
$target_dir = "../thumbnail-pictures/";
$target_file = $target_dir . basename($_FILES["thumbnail"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "Sorry, thumbnail file already exists. <br>";
$uploadOk = 0;
}
if ($_FILES["thumbnail"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded, ";
} else {
if (move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
HTML
<form action="" method="post" enctype="multipart/form-data" id="newpost">
<div class="col-lg-12">
<div class="form-group">
<label>Title</label>
<input class="form-control" name="title" id="title" required>
</div>
<div class="form-group">
<label>Video Thumbnail **Only JPEG & PNG is accepted**</label>
<input type="file" name="thumbnail" id="thumbnail" accept="image/png, image/gif, image/jpeg" >
</div>
The PHP code itself is working fine so I assume that the problem lies within the AJAX section, however I am unsure of how to solve this. Thankful for any help given!