I want to upload a file to a web server using HTML, JavaScript, and PHP.
My HTML looks like this:
<form method="post" enctype="multipart/form-data" name="uploadForm">
<input type="file" name="uploadFile" onchange="uploadplz();">
<!-- <input type="submit" name="upload_submit" value="Upload"> -->
</form>
The submit button is commented out because I have to use only one button to upload and submit the file. I have an onchange
attribute that call a JavaScript function. The JavaScript function then calls a PHP function using an AJAX call.
My JavaScript/AJAX looks like this:
<script type="text/javascript">
function uploadplz() {
$.ajax({
type: "POST",
url: "file.php",
data: "uploadForm",
success: function(response) {
alert(response);
}
});
}
</script>
PHP isset looks like this:
if(isset($_POST["uploadForm"])) {
upload_file();
}
PHP Function looks like this:
function upload_file() {
$dir = "files/";
$target_file = $dir.basename($_FILES["uploadFile"]["name"]);
echo $target_file."</br>";
if(move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file)) {
echo $target_file." uploaded successfully.</br>";
} else {
echo "Error uploading</br>";
}
}
When using 2 buttons, the PHP works fine i.e uploads file. I am assuming my AJAX is wrong when trying to use one button. The PHP function returns the Error uploading
message and a blank file name.
Any suggestions?