File Upload with Ajax ends in empty $_FILES array

Hello,
I am Uploading a File with Ajax, $_FILES seems to be correct if i inspect it with the debugging tool, still on the server side $_FILES is empty. If i submit the form with HTML only, $_FILES gets filled properly. Any clue on this? Maybe a wrong configuration somewhere ? i tried different implementations for submitting the file with js , all end in an empty $_FILES array on the server side, so it seems its not a js problem.

1 Like

in my View i have:

echo Html::beginForm(['picupload', 'kStammPerson' => $model->kStammPerson], 'post', ['enctype'=>'multipart/form-data' ,'id' => 'picform']);

echo Html::fileInput('pic', null, ['accept' => '.jpeg,.jpg', 'id' => 'picinput']);

echo Html::SubmitButton('uploaden', ['class' => 'btn btn-secondary','id'=>'picuploadbtn']);

echo Html::endForm();

echo '<div id="result"></div>';

in included js file i have:

function addPic(currentValue, index, arr){

  document.getElementById('result').innerHTML += '<img src=downloadpic?id='+currentValue.id+'>';
}

form.onsubmit =function(event){
  event.preventDefault();
  var formData = new FormData();
  formData.append("pic", fileSelect.files[0]);
  
  const urlParams = new URLSearchParams(window.location.search); 
  
  $.ajax({
      url: "picupload?kStammPerson="+urlParams.get('kStammPerson'),  //Server script to process data
      type: 'POST',

      
      data: formData,

      success: function(response) {
        const picids = JSON.parse(response);
        document.getElementById('result').innerHTML='';
        picids.forEach(addPic);
      },

      error: function(){
          alert('ERROR at PHP side!!');
      },

      cache: false,
      contentType: false,
      processData: false
  });
};

in Controller i have :

public function actionPicupload($kStammPerson = null)
    {
       return json_encode($_FILES);
}

what i get is that actionPicupload returns an empty array.
if i use just the form without js i get a proper upload.

Please use code tags. The code is unreadable for that reason. That </> icon on your comment editor

1 Like

I see now. Your problem is well articulated as well as solution provided.
Please check it out: