Search code examples
javascriptjquerygetjquery-eventsevent-delegation

Jquery hide and delete image after append and upload


I am trying to hide and delete image, this is the append code after upload

Append code

 $('#uploaded_images').append('<div class="container uploaded_image"> <input type="text" value="'+data['result']+'" name="uploaded_image_name[]" id="uploaded_image_name" hidden> <img class="img-thumbnail" width="200" height="200" src="server/uploads/'+data['result']+'" /> <a  id="delete" href="index.php?image='+data['result']+'" class="btn btn-danger">'+data['result']+'</a> </div>');

Hide code

$('body').on('click', '#delete', function() {
   // code here
   $(this).hide();
});

For some reason $(this).hide(); it's not working

I also would like to send a GET request to delete.php?image=+data['result']+ to delete the image from files.

Does somebody have a solution?


Solution

  • Here is working fiddle for hide / remove: https://jsfiddle.net/usmanmunir/wj2rLhus/5/

    $('body').on('click', '#delete', function() {
       $(this).parent().remove();
    });
    

    To Remove files from the server upload directory you can send delete.php?image=fileName

    In delele.php

    $FileName = $_GET['image']
    

    Store file name as you want by using the function implode in PHP

    $FileName = array('image1', 'image2', 'image3');
    $Dash_Added = implode("-", $array);
    
    echo $Dash_Added;
    

    unlink() will let you delete file from your upload directory if thats what you want.

    unlink('server/uploads'.$FileName)
    

    Upload file and store them to array

    <input type="file" onchange="SelectFiles(this)" multiple/>
    <input type="submit" onclick="UploadFiles(this)" value="Upload"/>
    
    
    <script>
    
    var allFileName = []
    
    function SelectFiles(_this) {
      for (var i = 0; i < _this.files.length; i++) {
       allFileName.push(_this.files[i]);
      }
    }
    
    function UploadFiles() {
    $.ajax({                 
      url:'haha.php',                 
      dataType:'json',                 
      type:'POST',                 
      cache:true,                 
      data: {                   
        file_names: allFileName                 
      },
      success: function(response) {
    
        }
      })
    }
    
    </script>
    

    Hope this helps.