Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

557
Views
Uploading image using FormData and Ajax not working, Undefined Index error message

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
over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!