Delete (rename) PHP figures with AJAX

Asked

Viewed 98 times

1

I have a page (up.php) that shows the following:

up.php

I want to do the following, by clicking Delete on any of them, show up a fa-Cog centered on the image and then remove it from there.

What I have so far does the job, but visually it’s bad:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<style>
.meio {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
}
</style>
<?php
$path = "img/";
$diretorio = dir($path);

while($arquivo = $diretorio -> read()) {
    if (substr($arquivo, 0, 6) == 'modelo' ) {
        $fotoscaminhocompleto[] = $path.$arquivo; 
        $nomearquivo[] = pathinfo($arquivo, PATHINFO_FILENAME);
        $extarquivo[] = pathinfo($arquivo, PATHINFO_EXTENSION);
    }
}
$diretorio -> close();

echo '<form method="post" id="apagarfoto" action="#">'; 
for ($x=0;$x<count($nomearquivo);$x++) {    
    echo '<div style="float: left; padding:5px;" align="center" id="'.$nomearquivo[$x].'">';
    echo $nomearquivo[$x].'<br />';
    echo '<input type="hidden" name="apagar" value="'.$nomearquivo[$x].'.'.$extarquivo[$x].'" />';
    echo '<img src="'.$path.'/'.$nomearquivo[$x].'.'.$extarquivo[$x].'" width="100px" /><br />';
    ?><button type="submit" onclick="myAjax('<?php echo $nomearquivo[$x]; ?>');"><i class="fa fa-trash"></i> Apagar</button><br /><?php
    echo '</div>';
}
echo '</form>';
?>
<script>
function myAjax(nome) {
    var nomediv = nome;
    $('#apagarfoto').submit(function(e) {
        e.preventDefault();
        var serializeDados = $('#apagarfoto').serialize();

        $.ajax({
            type: "POST",
            url: "foto_apagar.php",
            dataType: "html",
            data: serializeDados,       
            beforeSend: function() {
                document.getElementById(nomediv).innerHTML = '<div align="center"><i class="fa fa-spin fa-cog fa-3x"></i></div>';
            },
            complete: function() {
                document.getElementById(nomediv).innerHTML = "";
            },
            success: function (data, textStatus) {

            },
            error: function(xhr, er) {
                $("#resposta").html("Erro!");
            }
      });
    });
};
</script>

And the PHP page that executes the "delete" (actually renames) is as follows:

<?php
error_reporting(0);
ini_set(“display_errors”, 0 );
$base_dir = 'img/';
$retorno = rename($base_dir.$_POST['apagar'], $base_dir.'renomeado_'.$_POST['apagar']);
//sleep(3);
/*
if ($retorno == 1) {
    header("location: up.php");
} else {
    echo 'Nao foi possivel executar a operacao. Entre em contato com o webmaster da pagina.';
}
*/
?>

I know it’s a bit confusing but what I want is the following: Search in the folder "img" the figures that start with the name "model" and display them for the user to delete them if you want. The user will think they have deleted but they will remain in the folder, will only be renamed and will no longer appear.

In need of some supplementation I am at your disposal!

Thank you in advance!

1 answer

1


I believe you are doing it the wrong way. By clicking on the button you are firing two events at the same time, the click and the Submit.

No need to use this function myAjax(), you can use the event function. First thing is to remove the onclick and change the type to button. This button does not have the function of submitting the form, but only the function of a normal button. So it would be just like this:

<button type="button"><i class="fa fa-trash"></i> Apagar</button>

Now you create an event for the buttons. When one is clicked, it will take the id of the parent div and fire the Submit sending the id to the other event as parameter:

$("#apagarfoto button").on("click", function(e){
   var nomediv = $(e.target).closest("div").attr("id");
   $('#apagarfoto').trigger("submit", nomediv);
});

The other event, from Ubmit, you add one more parameter nomediv function and remove line var nomediv = nome;, because the variable nomediv is already in function. It will look like this:

$('#apagarfoto').submit(function(e, nomediv) {
  e.preventDefault();
  var serializeDados = $('#apagarfoto').serialize();

  $.ajax({
      type: "POST",
      url: "foto_apagar.php",
      dataType: "html",
      data: serializeDados,       
      beforeSend: function() {
          document.getElementById(nomediv).innerHTML = '<div align="center"><i class="fa fa-spin fa-cog fa-3x"></i></div>';
      },
      complete: function() {
          document.getElementById(nomediv).innerHTML = "";
      },
      success: function (data, textStatus) {

      },
      error: function(xhr, er) {
          $("#resposta").html("Erro!");
      }
});
});

Testing:

In the example below I put a setTimeout on complete: just to give a delay and illustrate how it works (copy the code I put above ):

$("#apagarfoto button").on("click", function(e){
   var nomediv = $(e.target).closest("div").attr("id");
   $('#apagarfoto').trigger("submit", nomediv);
});

$('#apagarfoto').submit(function(e, nomediv) {
  e.preventDefault();
  var serializeDados = $('#apagarfoto').serialize();

  $.ajax({
      type: "POST",
      url: "foto_apagar.php",
      dataType: "html",
      data: serializeDados,       
      beforeSend: function() {
          document.getElementById(nomediv).innerHTML = '<div align="center"><i class="fa fa-spin fa-cog fa-3x"></i></div>';
      },
      complete: function() {
         setTimeout(function(){  // apenas exemplo
          document.getElementById(nomediv).innerHTML = "";
         }, 3000); // apenas exemplo
      },
      success: function (data, textStatus) {

      },
      error: function(xhr, er) {
          $("#resposta").html("Erro!");
      }
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
<form method="post" id="apagarfoto" action="#">
<div style="float: left; padding:5px;" align="center" id="arquivo0">
   arquivo 0<br />
   <input type="hidden" name="apagar" value="arquivo0texto0" />
   <img src="" width="100px" /><br />
   <button type="button"><i class="fa fa-trash"></i> Apagar</button><br />
</div>
<div style="float: left; padding:5px;" align="center" id="arquivo1">
   arquivo 1<br />
   <input type="hidden" name="apagar" value="arquivo1texto1" />
   <img src="" width="100px" /><br />
   <button type="button"><i class="fa fa-trash"></i> Apagar</button><br />
</div>
</form>

  • Just perfect! I don’t know much about javascript and ajax, but I already got a good idea of what can be done! Thank you very much!

Browser other questions tagged

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