Uploading File Images with AJAX and PHP
I am attempting to create an upload document which will upload a profile picture. I am having trouble capturing the data from thechangePicture
form which only has an input for the images and a submit. I have never used theFormData
object to date, so I am still learning around this. Any guidance would be useful.
See my HTML
<form id="changePicture" method="post" enctype="multipart/form-data">
<div >
<label for="name">Update Your Profile Picture</label>
<input type="file" id="profilePic" name="profilePic">
<input type="hidden" value="<?php echo $id; ?>" name="id">
</div>
<button type="submit" id="updateProfileBtn" >Upload Image</button>
</form>
Here is my AJAX code:
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(result){
$("#spinner").hide();
$("#changePicture").append(result);
setTimeout(function(){
$("#changePicture").slideDown();
}, 1500);
}
});
}, 3000);
});
}
The PHP file at this moment only echos out "Working" to see it accesses the page alright, which it does. However, when I attempt to locate the file through a variable nothing has been sent and returnsundefined index
.
Answer
Solution:
this will be undefined because it's inside ajax's scope
Try:
As, for me, when using ajax I always prefer to base64encode the image and pass it as a JSON to PHP but i guess that's a personal preference...
Answer
Solution:
Why are you wrapping your AJAX call in a
?
By doing this, you cannot simply write
new FormData(this)
, because thethis
context does not refer to the form that you are looking for.Try executing the code without the timeout, or try storing the form data in a global variable
Edit: Example added: