Reputation: 2577
I have this ajax call which checks if the selected file names of a multiple file input already exist in the database. and if they do, it alerts a message telling them. The problem is I can only get it to alert all the file names from the result loop. how can I edit it so that it only alerts the file names that were selected? 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(~data.indexOf(fname)){
// only alert selected file names
alert("these files already exist:" + data);
return false;
}
}
},'json');
and in existing-filenames.php
$allfiles = $db->query("SELECT filename FROM files WHERE email = '$_SESSION[email]'");
$result = [];
while( $files = $allfiles ->fetch_assoc() ){
$result[] = $files['filename'];
}
echo json_encode($result);
and html
<input name = "file[]" type = "file" id = "file" multiple />
Upvotes: 0
Views: 164
Reputation: 584
Shouldn't you be alerting fname instead of data?
Here's how you do it:
myfiles = '';
for(var i = 0; i < file.files.length; i++)
{
if(~data.indexOf(fname)){
myfiles += fname;
}
}
if(myfiles !== ''){
alert("these files already exist:" + myfiles);
}
Does that make sense? We keep a running string of the files that we've added, and we alert them all at the end. You could add commas between them, or spaces, or whatever you want.
Upvotes: 0
Reputation: 44740
alert fname
instead of data
and remove return false;
if(~data.indexOf(fname)){
// only alert selected file names
alert("these files already exist:" + fname);
}
Upvotes: 0
Reputation: 318252
When in doubt, add more jQuery:
$('#file').on('change', function () {
var self = this;
$.get('existing-filenames.php', function (data) {
$.each(self.files, function () {
if (data.indexOf(this.name) != -1) {
alert("these files already exist:" + this.name);
}
});
});
});
Upvotes: 1