Search code examples
javascriptdropzone.jsdropzone

Javascript variable loses its value


Background: I use butSubmit to submit the form which has the Dropzone and some other fields - the dropzone is processed first, and if everything goes right than the fields are processed too

Problem: The files (from dropzone) are uploaded correctly, and error3 gets the DropzoneOK value. However, when I access the value on button click, it is shown empty. I tried with var error3="" outside the function too (that means, on line 4).

<script>
  $(document).ready(function() {
    Dropzone.autoDiscover = false;

    var myDropzone = new Dropzone('#myDropzone', {       
      autoProcessQueue: false,
      uploadMultiple: true,
      parallelUploads: 20,
      maxFiles: 20,
      addRemoveLinks: true,
      init: function() {
        this.on("errormultiple", function(){
          error3="DropzoneErr";
        });
        this.on("queuecomplete", function () {
          this.removeAllFiles();
        });
        this.on("successmultiple", function(file, response) {
          error3="DropzoneOK";   //It works
        });
      }
    });

    $('#butSubmit').click(function () {
       var error3="";
       myDropzone.processQueue();
       console.log(error3);  //error3 is shown to be empty
       if(error3!="DropzoneOK")
            error3 = "<p style='color:red'>Please try again</p>";
    });

  });
</script>

Solution

  • You're declaring this variable again with an empty value.

    $('#butSubmit').click(function () {
           var error3=""; <--- wrong, remove this
           myDropzone.processQueue();
           console.log(error3);  //error3 is shown to be empty
           if(error3!="DropzoneOK")
                error3 = "<p style='color:red'>Please try again</p>";
        });
    

    Once you've removed that line add var error3="" as the very first line like so:

    $(document).ready(function() {
        var error3="";
        Dropzone.autoDiscover = false;
    
        var myDropzone = new Dropzone('#myDropzone', {       
          autoProcessQueue: false,
    ...