Can you please take a look at this snippets and let me know what I am doing wrong to upload image to the img folder in the root directory?
I have simple inputs template like
Bug Title:<br>
<input type="text" name="bugTitle">
Bug Description:
<textarea name="bugDescriotion"></textarea>
Bug Image:<br>
<input type="file" id="input" name="bug-img">
and a jquery Ajax request like
$("#submit-bug").on("click", function(e) {
var mdata = new FormData();
mdata.append('bug_title', $('input[name=bugTitle]').val());
mdata.append('bug_description', $('input[name=bugDescriotion]').val());
mdata.append('bug_img', $('input[name=bug-img]')[0].files[0]);
e.preventDefault();
var request = $.ajax({
type: "POST",
url: "loadBugs.php",
data: mdata,
cache: false,
processData: false,
beforeSend: function() {
console.log(mdata);
}
});
request.done(function(data) {
console.log(data);
});
request.fail(function(jqXHR, textStatus) {
console.log("Request failed: " + textStatus);
});
});
and eventually a php filr called loadBugs.php
<?php
header('Content-type: application/json');
$validextensions = array("jpeg","jpg", "png");
$temporary = explode(".", $_FILES["bug_img"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["bug_img"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
if (file_exists("img/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "img/" . $_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
}
}
} else {
echo "<span id='invalid'>Invalid file Size or Type<span>";
}
?>
contentType: false,to your ajax.contentType: false,but no success! in the console I am getting a html format of error page