0

I'm trying to make an upload scrip with categories and I want to use XMLHttpRequest, the categories are with html select option, I do not know why the category does not update when I upload the file,I always get on the result page Cat 1,i have folowings codes:

function init() {
    var fileInput = document.getElementById('file-input');
    var uploadbutton = document.getElementById('upload');

 
 
    var yourSelect = document.getElementById("categ");
 
 cat = yourSelect.options[yourSelect.selectedIndex].value;
 
 
 
    var uploadProgress = document.getElementById('progress-amount');
    /////////////////////////////////////////////////////////////////
    uploadbutton.addEventListener('click', function () {
            xhr = new XMLHttpRequest();
            fd = new FormData();
            fd.append('file', fileInput.files[0]);
            fd.append('cat', cat);
  xhr.upload.onloadstart = function (e) {
            uploadProgress.value = 0;
            uploadProgress.max = e.total;
            uploadbutton.disabled = true;
        };
        xhr.upload.onprogress = function (e) {
            var percent = parseInt(e.loaded / e.total * 100);
   uploadProgress.style.width = percent + "%";
   document.getElementById("percent").innerHTML = percent + "%";
        };
        xhr.onloadend = function () {
            document.open();
            document.write(xhr.responseText);
      document.close();
        };
        xhr.open('POST', 'catch-file.php', true);
        xhr.send(fd);
    });
}

init();
<input type="file" id="file-input" name="filetoupload" accept="audio/mp3" required="required">
                
 <select size='1' id='categ' name="cat">
  <option value="1">Cat 1</option>
  <option value="2">Cat 2</option>
  <option value="3">Cat 3</option>
  <option value="4">Cat 4</option>
</select> 

In PHP i have this:

echo 'cat '.$_POST['cat'].'< br/>'.$_FILES['file']['name'];

if(move_uploaded_file($_FILES['file']['tmp_name'], 'test/' . $_FILES['file']['name'])){
  echo '<br/>succes :)';
}    

Image

Chris
  • 4,672
  • 13
  • 52
  • 93
BOGDAN
  • 1
  • Can you show how you are creating your form? Please post complete HTML – SG_Rowin Nov 03 '17 at 18:36
  • Please format your PHP code as code (indent 4 spaces) – Heri Nov 03 '17 at 18:37
  • Can you confirm cat was selected with console.log(cat), also not seeing you sending headers: https://stackoverflow.com/a/9713078/3254405 – boateng Nov 03 '17 at 19:25
  • 1
    Solved,i moved `var yourSelect = document.getElementById("categ"); cat = yourSelect.options[yourSelect.selectedIndex].value; ` inside of addEventListener and now is working :) – BOGDAN Nov 04 '17 at 19:13

0 Answers0