Below is the ajax request.
$.post(\'delete.php\', {\'deletearray\':deletearray, \'dir\':dir}, function(deleted, undeleted){
if(undeleted == 0) {
aler
You should use json_encode
like following:
json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted));
And you have to get vars with data.undeleted
and data.deleted
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(data) {
if(data.undeleted == 0) {
alert('All ' + data.deleted + ' files delted from the server');
} else {
alert(data.deleted + ' files deleted and ' + data.undeleted + ' files could not be deleted');
}
}, 'json');
The best way to do jquery + ajax + php is as next:
jquery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function do_ajax() {
//set data
var myData = new Array();
myData.push({name:'deletearray',value:'deletearray'});
myData.push({name:'dir',value:'dir'});
//ajax post
$.ajax({
dataType: 'json',
url: 'delete.php',
type: 'post',
data: myData,
success: function(returnData) {
if(returnData.undeleted == 0) {
alert('All ' + returnData.deleted + ' files delted from the server');
} else {
alert(returnData.deleted + ' files deleted and ' + returnData.undeleted + ' files could not be deleted');
}
}
});
}
</script>
PHP:
<?php
$myData = $_POST;
if(isset($myData['deletearray']) AND isset($myData['dir'])) {
$files = $myData['deletearray'];
$dir = $myData['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
print(json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted)));
exit();
}
?>
First thing-
Use $_POST['deletearray']
instead of $_POST[deletearray]
Second thing-
You cannot return different variables from the PHP scrtipt, every thing you print there is returned in the ajax callback, so just write this-
PHP
json_encode(array('totalDeleted' => $deleted, 'totalUndeleted' => $undeleted));
AJAX
...
function(response){
response=JSON.parse(response);
console.log(response);
}