I'm using FormData and Ajax to pass a file to upload from the View to the Controller in Codeigniter. Passing the uploaded file has to be made using Ajax. Below is the code I'm using. If I don't include the line form.append("photoToUpload", fileToUpload.files[0]);, the passing of data. But it does not work if form.append("photoToUpload", fileToUpload.files[0]); is included. The error displayed is "Undefined Index: photoToUpload".
Using the line console.log(fileToUpload.files[0]); actually displays the details of the image I'm trying to upload. And I used for (var pair of form.entries()) { console.log(pair[0]+ ', ' + pair[1]); } to confirm the contents of the FormData before calling Ajax to make sure it has the right contents.
Additional information : The code works in localhost but not on the live server. Server has a bit higher PHP version but still 7.2, has the same Jquery version. Not sure what else to check.
var fileToUpload = document.getElementById('photoToUpload');
// To check if fileToUpload has the contents
console.log(fileToUpload.files[0]);
var form = new FormData();
form.append("photoToUpload", fileToUpload.files[0]);
form.append("caption", "Sample caption");
// To check if the FormData has the contents
for (var pair of form.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
url : "addToDB",
type : "POST",
data : form,
cache : false,
contentType : false,
processData : false,
success : function(response) {
console.log(response);
}
});
Backend:
echo $_POST['caption'];
echo $_FILE['photoToUpload']['name'];
// This also work in displaying the data passed in array format
print_r($_POST); // Displays photoToUpload as undefined
print_r($_FILES); // Empty array for photoToUpload