Reputation: 1247
I'm trying to get a simple upload system going using php and XMLHttpRequest. However I fail to achieve the goal using the request. It doesn't work..
Here is my HTML form which is used to get the image file:
<form action="../session/uploader.php" method="post" enctype="multipart/form-data" id="uploadForm">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
and this is my PHP script which saves the image into my filesystem:
<?php
if(isset($_POST["submit"])) {
$target_dir = "../db/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
?>
Now this works perfectly fine but I want to use an XMLHttpRequest so that the page doesn't need to refresh when images are uploaded. I was trying to do something which seemed very straight forward but it didn't work..
first I changed the PHP to this:
<?php
$target_dir = "../db/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
?>
and right below my form in the HTML I've added some Javascript which makes the XMLHttpRequest and sends it:
<script>
const uploadForm = document.getElementById("uploadForm");
uploadForm.addEventListener("submit", function(e) {
e.preventDefault();
const xhr = new XMLHttpRequest();
xhr.open("POST", "../session/uploader.php", true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(new FormData(uploadForm));
});
</script>
The problem here is that it simply doesn't work. Nothing happens. I get no feedback. It's like the uploader.php script didn't get called.
Doesn anyone know what the problem might be?
Upvotes: 0
Views: 415
Reputation: 5820
if(isset($_POST["submit"]))
The submit button will not be included in the form submission data set here, as it would be if you had just send the form “normally”.
xhr.send(new FormData(uploadForm));
The browser has no idea here at this point, that you clicked the submit button to actually trigger the whole process - so it will only include the data for the fileToUpload
file upload field, but not the submit button.
You can either add a hidden field, and then check if that is set within $_POST, or you check if fileToUpload
is set directly (but remember, that one is going to be in $_FILES, not $_POST.)
xhr.setRequestHeader("Content-Type", "multipart/form-data");
A proper multipart request also needs to include the boundary that will be used to separate the parts inside the request body, in this header.
Using FormData, this should automatically get added, so remove this line - it is overwriting the correct header with one that is incomplete here at this point.
Upvotes: 2