Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

559
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda