Problem with deleting data from database using ajax and php
I am working on a cms for properties/ads in oop php for learning purposes. I am trying to delete photos from database using ajax and php. I am having trouble when I click on X button on photo in my view it removes it, but when I refresh page it pops back up again, and also it doesn't remove it from database. Any help is greatly appreciated. Here is my code:
index.php:
<?php foreach ($data1 as $key => $value) : ?>
<?php if($key == 1) { ?>
<div >
<span >×</span>
<img src="<?php echo '/public/photos/'.$value->name.'.'.$value->extension ?>" data-id="<?php echo $value->name ?>" width="150" height="150">
</div>
<?php } else { ?>
<div >
<span >×</span>
<img src="<?php echo '/public/photos/'.$value->name.'.'.$value->extension ?>" data-id="<?php echo $value->name ?>" width="150" height="150">
</div>
<?php } ?>
<?php endforeach; ?>
<script>
$('.img-wrap .close').on('click', function() {
var that = this;
var id = $(that).closest('.img-wrap').find('img').data('id');
var confirmation = confirm("Are you sure you want to delete this picture?");
if (confirmation) {
$.ajax({
url: 'ads/deletephoto',
//dataType: 'json',
type: 'post',
contentType: 'application/json',
data: JSON.stringify( { "name": id } ),
processData: false,
success: function( data, textStatus, jQxhr ) {
console.log( $(that).closest('.img-wrap') );
$(that).closest('.img-wrap').hide();
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
});
</script>
AdModel:
public function deletePropertyPhoto($id)
{
$this->db->query('DELETE FROM photos WHERE id=(SELECT photo_id FROM property_photo WHERE property_id=:property_id)');
$this->db->bind(':property_id', $id);
$this->db->execute();
$this->db->query('DELETE FROM property_photo WHERE property_id=:property_id');
$this->db->bind(':property_id', $id);
$this->db->execute();
}
AdsController:
public function deletePhotoAction()
{
$userinfo = $this->Auth->Auth(['admin', 'moderator']);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$this->Auth->isSet($_GET['id'], "ads/index");
$photo = $this->AdModel->deletePropertyPhoto($_GET['id']);
if ($photo != false) {
if (file_exists('public/photos/' . $photo->photo)) {
unlink('public/photos/' . $photo->photo);
}
}
redirect('ads/index');
echo "Property is not found!!!";
}
}