1

in my code, the user enters a name for an output file. I check if this file name is already existing, if yes, ask the user if overwrite or not. Here follows my code:

var outputs_array = new Array();
[..]
var output_form = document.getElementById(form_id);

output_form.onsubmit = function(e) {
 e.preventDefault();
 var output_file = output_form.querySelector("[name="+output.name+"]").value;
 let [usr_filename, usrfileExtension] = output_file.split(/\.(?=[^\.]+$)/);
 var format_in = "txt";
 // build up the url to retrieve only files with given format
 var file_list_format_in =  serverURI + "/resources?formats=" + format_in + "";
 var isFileNameOk = 0;
 $.getJSON(file_list_format_in, function(data){
    $.each(data.resources, function(j, resource){
       let [res_filename, resfileExtension] = resource.name.split(/\.(?=[^\.]+$)/);
       if(usr_filename == res_filename){
         if(confirm("A file with that name already exists. Overwrite?")){
           isFileNameOk = 1;
           console.log("OVERWRITE " + outputs_array);
          } else {
           console.log("NOT OVERWRITE ");
          }
        } else {
          isFileNameOk = 1;
          console.log("NOT exists ");
        }
     }); // each resource
     if (isFileNameOk) {
        outputs_array.push(output_file);
     }
 }); // resource file list JSON
 console.log("OUTPUT outputs_array " + outputs_array);
} // onsubmit form

My goal is to fill the output_array with the names of given output files. The desired behaviour is as follow:

  • on form submit, get the list of existing file (file_list_format_in),
  • loop over each existing file and check if anyone has the same name as the user usr_filename
  • if YES, then a pop-up dialog asks the user if overwrite or not. -> if YES, then set the isFileNameExisting to 1
  • if NO, do not change isFileNameExisting (remains 0)
  • Finally, if the usr_filename does not exists then push the output_file to the outputs_array My code does not work, if I enter an existing file name and say yes to overwrite, the output_file is not pushed to outputs_array. I'm getting crazy to make my logic work as expected.

Thank you for any help you could provide.

user123892
  • 1,243
  • 3
  • 21
  • 38
  • does this `console.log("NOT exists ");` show in console ? – Swati Dec 22 '20 at 14:47
  • @Swati yes, it does.. – user123892 Dec 22 '20 at 14:58
  • The problem is that you are outputting `outputs_array` immediately, while your ajax requests are asynchronous, and so the `outputs_array` will be populated later. It is a common problem, and the linked Q&A has all the info on it. – trincot Dec 22 '20 at 15:03
  • @trincot: okay, thank you. Right now I can't check the link you shared but sounds like explaining my issue. – user123892 Dec 22 '20 at 15:19

0 Answers0