Button to delete PHP photo with Jquery

Asked

Viewed 561 times

0

Good afternoon. I need to include a button in my editing form so I can delete the user’s photo. I’d like to do with jquey and ajax, I’m still learning. I’m using mysql that stores only the photo path, the file stays in a folder on the server. Someone could give at least one way to go... 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 end of the page:

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

1 answer

1


Use Ajax in jquery by clicking the button to run 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 search the database for the code of your photo, and use the function unlink php to remove the file. (http://php.net/manual/en/function.unlink.php)

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

if (is_file($path.'/'.$file)) { 
     @unlink($path.'/'.$file); 
  } 
  • That’s what I wanted to do !!! show. Now let me ask you something, in this form where there is this delete photo button, at the end of it there is a Ubmit button, which at the time I click on the delete photo button it ends up running Submit.. I was stupid not to mention it in the question. I am looking for a solution.

  • If you have used <input type="submit" just change to <input type="button" so it will have function of a common button and not a form Submit. The type=Submit in the q tag is responsible for submitting your form.

  • Do not forget after setting the answer as chosen ta?? so help me with a few points kkk

  • type after that the person helps you here in the forum and the answer helped you with the problem, just click q nor indicated in this image, to select the correct answer. https://i.imgur.com/Jnf5v0l.png This helps those who are helping you, and also makes the forum more organized

  • Samanta you were spectacular!!! Thank you very much!!

  • Denada, I’m happy to help. bjss

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.