简体   繁体   中英

checking exisiting filenames against muliple file input

I have a file verification process which checks if a filename is already in the database by making an ajax call. This works if there is only 1 filename echoed in existing-filenames.php, but I can't figure out how I can loop through the return data to check every filename in the multiple file input against every result from the existing-filenames.php loop. any advice much appreciated. thanks

var file = $('#file')[0];
$.get('existing-filenames.php', function(data){

  for (var i=0; i<file.files.length; i++) {
       var fname = file.files[i].name;

        if(fname == data){ 
          alert("these files already exist:" + data); 
          return false;
        }
      }
  });

and in 'existing-filenames.php'

$allfiles = $db->query("SELECT filename FROM files WHERE email = '$_SESSION[email]'");

    while($result = $allfiles ->fetch_assoc()) {
    echo $result['filename'];
}

In your PHP file you're just printing all file paths without a space or a new line. Also you should use prepared statements for your query, include $_SESSION['email'] without any check is not safe at all.

By the way, try edit your PHP file like this:

$allfiles = $db->query("SELECT filename FROM files WHERE email = '$_SESSION[email]'");

$fileList = array();
while($result = $allfiles ->fetch_assoc()) {
    $fileList[] = $result['filename'];
}

echo json_encode($fileList);

And your JS code like this:

$.get('existing-filenames.php', function(data){
      for (var i=0; i<file.files.length; i++) {
       var fname = file.files[i].name;

        if(data.indexOf(fname) >= 0){ 
          alert("these files already exist:" + data); 
          return false;
        }
      }
  }, 'json');

Not tested, but it should work

Try changing your JS to:

var file = $('#file')[0];
$.getJSON('existing-filenames.php', function(data){

  for (var i=0; i<file.files.length; i++) {
     var fname = file.files[i].name;

      if(~data.indexOf(fname)){ 
        alert("these files already exist:" + data); 
        return false;
      }
  }
});

And in your PHP file:

$result = [];
while( $files = $allfiles ->fetch_assoc() ){
    $result[] = $files['filename'];
}
echo json_encode($result);

... I think. I hardly ever write PHP.

var fileNames = $('.file-name').text();

fileNames.forEach(function(fileName){
     $.get('url',{filename: fileName},function(data){
                  ....
       });
 });

My approach would be getting the filenames into an array and making the get request with different parameters each time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM