0
I have the following image upload code but it only works if the js is on the same form page and does not work coming from external file js, I would like to use external because I use other functions, Could someone explain to me why the external js does not work or give some hint? grateful!
HTML
<head>
<title>Image Upload Form</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/teste.js"></script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" ">
<label>Select a file:</label><br>
<input type="file" name="file" required onchange='return submitForm();'/>
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
external js
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "../teste.php",
type: "POST",
data: fd,
processData: false,
contentType: false
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
Php
if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $filename);
echo "Stored in: " . "upload/" . $filename;
}
}
} else {
echo "Invalid file";
}
?>
that was it! thank you!
– Jonatan Gonsales