Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Olá Utilizo um sistema de cadastro de notícias com campos para imagens. Na parte de edição das notícias, existe um checkbox que, ao selecionado, exclui a imagem quando clicado no Atualizar e a página é recarregada e o PHP executado. /monthly_2020_02/IMAGEM1.jpg.73631cf3d20994b4a4b8cc06041f9f9e.jpg" style="width:600px. height:auto. " alt="IMAGEM1.jpg.73631cf3d20994b4a4b8cc06041f9f9e.jpg" /> Mas eu queria mudar isso. Gostaria que a imagem fosse excluída sem dar um refresh na página. Seria algo como na imagem abaixo: você clica no botão Excluir, aparece uma mensagem se deseja realmente excluir a imagem e você confirma sem recarregar a página. /monthly_2020_02/IMAGEM2.jpg.9253215223b31d14ba7c61af417e3a71.jpg" style="width:600px. height:auto. " alt="IMAGEM2.jpg.9253215223b31d14ba7c61af417e3a71.jpg" /> Tem como fazer? Fico grato por qualquer dica.
Olá
Então, segue abaixo o trecho que cadastra ou exclui a imagem do servidor e do banco de dados:
//IMAGEM 1
if ($_POST['exc1'] == null)
{
if ($_FILES['img1']['name'] != null)
{
$carregar1 = WideImage::loadFromUpload('img1');
$imagem1 = $carregar1->resize(572, '1000', 'inside', 'down');
$watermark1 = WideImage::load('../assets/files/informativos/marcadagua.gif');
$imagemfinal1 = $imagem1->merge($watermark1, "right -25", "bottom -35", 80);
$nomeimagem1 = time().'_'.rand(10,99).".jpg";
$local1 = '../assets/files/informativos/'.$nomeimagem1;
$imagemfinal1->saveToFile($local1, 70);
} else {$nomeimagem1 = $img1;}
} else {
unlink('../assets/files/informativos/'.$img1);
$nomeimagem1 = null;
}
e abaixo o trecho em HTML:
<input name="img1" type="file" class="span6" id="img1"><br />
<img src="../assets/files/informativos/<?php echo $img1; ?>" width="80px" />
<input name="exc1" type="checkbox" id="exc1" value="1" style="margin-left:20px;" /> Selecione para excluir esta imagem.
basta marcar o checkbox, clicar **Atualizar **e a imagem é excluida.
Mas gostaria de excluir ela sem precisa recarregar a página.Segue exemplo, abaixo:
INDEX.PHP:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> EXAMPLE </title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
Imagem 1:<input type="checkbox" class="exc1" name="exc1" value="imagem1.png" />
<br />
Imagem 5:<input type="checkbox" class="exc1" name="exc1" value="imagem5.png" />
<br />
<button class="deletar">Deletar</button>
<script type="text/javascript">
$(function()
{
$('.deletar').click (function()
{
var selected = new Array();
// Coloca os valores em um array
$('.exc1:checked').each(function(){
selected.push($(this).val());
});
// Deleta via AJAX
$.ajax({
url: "http://localhost/deleta.php",
type: "POST",
data: {
imagens: selected
},
success: function (msg){
alert(msg);
}
});
});
});
</script>
</body>
</html>
**DELETA.PHP**
<?php
if(isset($_POST['imagens'])){
$relatorio = "";
foreach ($_POST['imagens'] as $img){
$path = "caminho/arquivo/" . $img;
if(@unlink($path)){
$relatorio.= "O arquivo '{$img}' foi deletado!\n";
}else{
$relatorio.= "Falha ao deletar o arquivo '{$img}'!\n";
}
}
echo $relatorio; echo "Selecione uma imagem!";
}>
Em 07/02/2020 at 15:13, Artes Ussler disse:
<input name="img1" type="file" class="span6" id="img1"><br />
<img src="../assets/files/informativos/<?php echo $img1; ?>" width="80px" />
<input name="exc1" type="checkbox" id="exc1" value="1" style="margin-left:20px;" /> Selecione para excluir esta imagem.
JS e CSS necessários:
[https://github.com/Spell-Master/sm-web/tree/master/javascript/AjaxRequest](https://github.com/Spell-Master/sm-web/tree/master/javascript/AjaxRequest)
<input name="img1" type="file" class="span6" id="img1"><br />
<img src="../assets/files/informativos/<?= $img1; ?>" width="80px" />
<input name="exc1" type="checkbox" id="exc1" value="1" style="margin-left:20px;" /> Selecione para excluir esta imagem.
<div id="executa_ajax"></div>
<script>
document.getElementById('exc1').addEventListener('change', apagaImagem, false);
function apagaImagem(e) {
var alvo = e.target;
var imagem = alvo.previousElementSibling; // Obtenho a imagem
if (alvo.checked) { // O checkbox deve está marcado
apagaImagem.prototype = new AjaxRequest();
apagaImagem.prototype.open('executa_ajax', 'arquivo_que_apaga.php?alvo=' + imagem.src + '&id=' + imagem.id);
}
}
</script>
Com isso ao marcar o checkbox iniciamos a classe AjaxRequest que irá carregar o arquivo responsável por apagar a imagem enviando um $_GET['alvo'] com exatamente o src da imagem, com essa informação então é só apagar a imagem. Ainda nesse arquivo enviamos também o #ID da imagem então ao excluir a imagem podermos usar o seguinte script:
document.getElementById('<?= $_GET['id'] ?>').src = null;
Assim sendo ao apagar a imagem removemos também ela do html.
Demais exemplos de uso no AjaxRequest você encontra no arquivo exemplo.html no link citado acima.
Caso interesse também criei alguns scripts dito próprio para uploads:
[https://github.com/Spell-Master/sm-web/tree/master/javascript/FileTransfer](https://github.com/Spell-Master/sm-web/tree/master/javascript/FileTransfer)
[https://github.com/Spell-Master/sm-web/tree/master/exemplos/corte-e-salvamento-de-imagens](https://github.com/Spell-Master/sm-web/tree/master/exemplos/corte-e-salvamento-de-imagens)
Seria melhor se tivesse o HTML do formulário aí.
Pois existem duas formas simples para fazer isso, enviando uma requisição GET ou POST ambos poderiam ser enviadas por AJAX.
Não vou mostrar um exemplo por desconhecer a estrutura html do formulário, pois teria que saber como chegar até essa imagem, ou mesmo pode haver mais de um formulário como esse na página.