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:


<?php foreach ($data1 as $key => $value) : ?>

  <?php if($key == 1) { ?>
  <div >
    <span >&times;</span>
    <img src="<?php echo '/public/photos/'.$value->name.'.'.$value->extension ?>" data-id="<?php echo $value->name ?>" width="150" height="150">
  <?php } else { ?>
  <div >
    <span >&times;</span>
    <img src="<?php echo '/public/photos/'.$value->name.'.'.$value->extension ?>" data-id="<?php echo $value->name ?>" width="150" height="150">
         <?php } ?>

<?php endforeach; ?>

$('.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) {
      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') );
      error: function( jqXhr, textStatus, errorThrown ){
        console.log( errorThrown );


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->query('DELETE FROM property_photo WHERE property_id=:property_id');
  $this->db->bind(':property_id', $id);


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);

          echo "Property is not found!!!";

People are also looking for solutions to the problem: php - Add data to collection before pagination in Laravel


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.