Button to delete PHP photo with Jquery

0

Good afternoon. I need to include a button on my edit form so that I can delete the user's photo. I would like to do with jquey and ajax, I'm still learning. I am using mysql which stores only the path of the photo, the file is in a folder on the server. Could someone give at least one way forward ... or some idea Below is my code:

<div class="form-group">
        <label for="foto_aluno" class="col-sm-2 control-label">Alterar foto</label>
        <div class="col-sm-10">
            <input type="file" class="form-control-file" id="foto_aluno" name="arquivo">
    </div>

    </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
            <button  class="btn btn-danger btn-sm" id="btn_excluir">Excluir foto</button>
            </div>
     </div>

At the bottom of the page:

<script type="text/javascript">
$(document).ready(function(){
     $('#btn_excluir').click(function(){
        alert('Aqui o código para excluir');
     })
 })
</script>
    
asked by anonymous 13.03.2018 / 20:23

1 answer

1

Use Ajax in jquery when clicking the button to execute the script in php

<script type="text/javascript">
$(document).ready(function(){
     $('#btn_excluir').click(function(){

$.ajax({method: "POST", url: "linkdoseuscript.php",
            data: { codigodafoto: "xxxxxx" }
       }).done(function( msg ) {
            alert( "Resposta do php: " + msg );
      });


     })
 })
</script>

Then inside your php script you'll search the database for your photo's code, and use php's unlink function to remove the file. ( link )

Just be careful with this function to not delete what you should not, use a check before the file actually exists with is_file for example:

if (is_file($path.'/'.$file)) { 
     @unlink($path.'/'.$file); 
  } 
    
13.03.2018 / 22:15