Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

574
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda