Reputation: 2577
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'];
}
Upvotes: 0
Views: 57
Reputation: 14466
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.
Upvotes: 1
Reputation: 849
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
Upvotes: 1
Reputation: 2412
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
Upvotes: 1