Jump to content
Sign in to follow this  
t0ze

[Resolvido] Eliminar registo em tabela depois de Confirmation message

Recommended Posts

t0ze

Bom dia,

Estou com a seguinte dúvida.

Tenho nos registos de uma tabela um link que aponta para um script PHP q vai eliminar aquele registo.

<td><a href="registry_edit.php?id_registry=1364" class="edit">Editar </a>| <a class="remove" href="includes/delete_registry.php?registry_id=1364"> Eliminar</a> </td>

Tenho aqui feito um pedaço de código que me mostra a Confirmation Message:

<a id='confirm' href="#" class="">Demo</a>
   <script>
       $('#confirm').click(function(){
           $.showMessageBox({
               content:"OK or close!",
               title: 'Apagar Registo',
               OkButtonDoneFunction: function() {
                   alert('Pressed OK!');
               },
               type:'question'
           });
       });

   </script>

Agora a minha dúvida, é aqui, em vez de enviar um alert como é q eu redirecciono para aquele script php que elimina o registo.

Terei que na tabela e no link de Eliminar por o ID="confirm"... Só que não sei como passar o endereço do scrpit php que elimina para o Javascrip.

Share this post


Link to post
Share on other sites
t0ze

Obrigado,

Isto ainda é novo para mim... peço compreensão/paciência.

<a id='confirm' href="#" class="">Demo</a>
   <script>
    $('#confirm').click(function(){
	    $.showMessageBox({
		    content:"OK or close!",
		    title: 'Apagar Registo',
		    OkButtonDoneFunction: function() {
                 $.post("includes/delete_registry.php?registry_id=$id");
		    },
		    type:'question'
	    });
    });

   </script>

Não funciona :S

Share this post


Link to post
Share on other sites
yoda
<a class='confirm' data-cid="<?php echo $id; ?>" href="#">Demo</a>
<script>
 var id = false;
 $('.confirm').click(function(){
	 id = $(this).attr('data-cid');
	 $.showMessageBox({
		 content:"OK or close!",
		 title: 'Apagar Registo',
		 OkButtonDoneFunction: function() {
			 $.post("includes/delete_registry.php?registry_id="+id);
		 },
		 type:'question'
	 });
 });

</script>

Edited by yoda
  • Vote 1

Share this post


Link to post
Share on other sites
t0ze

Obrigado yoda,

Resultou na perfeição, porém e já agora de forma a melhor perceber. Este data-cid="" não encontrei informação a explicar este atributo. É neste atributo que devemos colocar, os valores que queremos usar dentro do jquery? ( $(this).attr('data-cid');)

Share this post


Link to post
Share on other sites
t0ze

Não sei se hei-de criar um novo tópico ou se é possivel marcar este de novo como "Não Resolvido".

O que o yoda me ensinou é valido, funciona. Mas adaptei aquele exemplo a um outro cenário em que a tabela e aquele link de delete está a ser criado pelo javascript algo assim:

function pageselectCallback(page_index, jq){
		    // Get number of elements per pagionation page from form
		    var newcontent ='';
		    var items_per_page = $('#items_per_page').val();
		    var max_elem = Math.min((page_index+1) * items_per_page, <?php echo @registry_count_all(); ?>);
		    var newcontent = '<tr><th>Nº Registo</th><th>Nome</th><th>Data Pedido </th>';
			    newcontent += '<th>NIN</th><th>Data </th><th>Resolvido</th><th>Nº LN</th><th>Nº LA</th>';
			    newcontent += '<th>Finalizado</th><th></th>';
		    // Iterate through a selection of the content and build an HTML string

		    for(var i=page_index*items_per_page;i<max_elem;i++)
		    {
			    newcontent += '<tr>';
				    newcontent += '<td class="rightCell"><a class="link" href="'+'registry_show.php?id_registry=' + members[i][0] + '">'+ members[i][1] +'</a>'+'</td>';
				    newcontent += '<td>' + members[i][2] + '</td>';
				    newcontent += '<td>' + members[i][3] + '</td>';
				    newcontent += '<td class="rightCell">' + members[i][4] + '</td>';
				    newcontent += '<td>' + members[i][5] + '</td>';
				    newcontent += '<td>' + members[i][6] + '</td>';
				    newcontent += '<td class="rightCell">' + members[i][7] + '</td>';
				    newcontent += '<td class="rightCell">' + members[i][8] + '</td>';
				    newcontent += '<td>' + members[i][9] + '</td>';
				    newcontent += '<td><a href="'+'registry_edit.php?id_registry=' + members[i][0] + '" class="edit">Editar </a>'+'<?php if(@is_admin()==1){ echo "| <a href=\"#\"id=\"confirm\" >!!!!</a>"; } ?></td>';
			    newcontent += '</tr>';
			    /*newcontent += '<dd class="state">' + members[i][2] + '</dd>';
			    newcontent += '<dd class="party">' + members[i][3] + '</dd>';*/
		    }

Isto constroi a tabela e na tabela (inspeccionando o elemento no chrome) -

Tenho este link que não faz nada

<td> <a href="#" id="confirm" data-cid="265">Eliminar</a></td>

Porem fora da tabela tenho exactamente o mesmo que funciona.

<a id="confirm" data-cid="260" href="#">Eliminar</a>

Sinto-me um bocadinho perdido e não sei se aquela forma de alimentar a tabela é a mais correcta .. nem sei porque é que isto não funciona ..

Share this post


Link to post
Share on other sites
t0ze

function pageselectCallback(page_index, jq){
			// Get number of elements per pagionation page from form
			var newcontent ='';
			var items_per_page = $('#items_per_page').val();
			var max_elem = Math.min((page_index+1) * items_per_page, <?php echo @registry_count_all(); ?>);
			var newcontent = '<tr><th>Nº Registo</th><th>Nome</th><th>Data Pedido </th>';
				newcontent += '<th>NIN</th><th>Data </th><th>Resolvido</th><th>Nº LN</th><th>Nº LA</th>';
				newcontent += '<th>Finalizado</th><th></th>';
			// Iterate through a selection of the content and build an HTML string

			for(var i=page_index*items_per_page;i<max_elem;i++)
			{
				newcontent += '<tr>';
					newcontent += '<td class="rightCell"><a class="link" href="'+'registry_show.php?id_registry=' + members[i][0] + '">'+ members[i][1] +'</a>'+'</td>';
					newcontent += '<td>' + members[i][2] + '</td>';
					newcontent += '<td>' + members[i][3] + '</td>';
					newcontent += '<td class="rightCell">' + members[i][4] + '</td>';
					newcontent += '<td>' + members[i][5] + '</td>';
					newcontent += '<td>' + members[i][6] + '</td>';
					newcontent += '<td class="rightCell">' + members[i][7] + '</td>';
					newcontent += '<td class="rightCell">' + members[i][8] + '</td>';
					newcontent += '<td>' + members[i][9] + '</td>';
					newcontent += '<td><a href="'+'registry_edit.php?id_registry=' + members[i][0] + '" class="edit">Editar </a>'+'<?php if(@is_admin()==1){ echo "| <a href=\"#\"class=\"confirm\" >Eliminar</a>"; } ?></td>';
				newcontent += '</tr>';
				/*newcontent += '<dd class="state">' + members[i][2] + '</dd>';
				newcontent += '<dd class="party">' + members[i][3] + '</dd>';*/
			}

Isto constroi a tabela e na tabela (inspeccionando o elemento no chrome) -

Tenho este link que não faz nada

<td> <a href="#" class="confirm" data-cid="265">Eliminar</a></td>

E aqui

<script>
	 var id = false;
	 $('.confirm').click(function(){
			 id = $(this).attr('data-cid');
			 $.showMessageBox({
					 content:"OK or close!",
					 title: 'Apagar Registo',
					 OkButtonDoneFunction: function() {
							$.post("includes/delete_registry.php?registry_id="+id);
					 },
					 type:'question'
			 });
	 });
</script>

Aparentemente, está ok assim?

Continua sem dar a mensagem de confirmação.

Edited by t0ze

Share this post


Link to post
Share on other sites
yoda

Experimenta assim :

			 $('.confirm').click(function(e){
							 e.preventDefault();
							 id = $(this).attr('data-cid');

Outra coisa, carrega a tabela que estás a construir completa do servidor em vez de fazeres como tens agora, fica mais leve para o browser e mais simples de usar.

Edited by yoda

Share this post


Link to post
Share on other sites
t0ze

Obrigado yoda,

Testei e continuei sem sucesso.

Entretanto dei uma martelada nisto assim

<a onclick="ConfirmDelete(253)" class="confirm" data-cid="253" href="#">Eliminar</a>

E depois na função javascript

<script>
function ConfirmDelete(id){

$(function(){
			  //e.preventDefault();
			  $.showMessageBox({
				    content:id,
				    title: 'Apagar Registo',
				    OkButtonDoneFunction: function() {
						    //$.post("includes/delete_registry.php?registry_id="+id);
						    $(window.location).attr('href', 'includes/delete_registry.php?registry_id='+id);
				    },
				   type:'question'
			 });
	 });
}
</script>

Acontece que agora sim, a mensagem de confirmação aparece, mas não consigo obter o ID, nesse exemplo dá-me um undifened

Alguma sugestao

Share this post


Link to post
Share on other sites
t0ze

Obrigado pela chamada de atenção yoda, aqui, mais que tudo gostava de aprender e em vez de dar marteladas, fazer as coisas pela forma certa. Deixo a pagina completa como a estou a contruir.

<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php");?>
<?php include('./lang/language.php');?>
<?php include("includes/html.php"); ?>
<?php include("includes/header.php"); ?>
<?php include("includes/logininfo.php");
confirm_logged_in();
$default = $_SESSION['user_lang'];?>
<?php include("includes/menu.php"); ?>
<?php include("includes/pagination.php"); ?>
</div>
<?php
if (isset($_POST['search'])) {
 $_SESSION['registry'] = $_POST['NinName'];
}
if (isset($_POST['restart'])) {
 $_SESSION['registry'] = "";
}
//echo @is_admin();
echo @get_registry();//Array de members
?>
<script type="text/javascript">
		// This file demonstrates the different options of the pagination plugin
		// It also demonstrates how to use a Javascript data structure to
		// generate the paginated content and how to display more than one
		// item per page with items_per_page.
		/**
		 * Callback function that displays the content.
		 *
		 * Gets called every time the user clicks on a pagination link.
		 *
		 * @param {int}page_index New Page index
		 * @param {jQuery} jq the container with the pagination links as a jQuery object
		 */
		function pageselectCallback(page_index, jq){
			// Get number of elements per pagionation page from form
			var newcontent ='';
			var items_per_page = $('#items_per_page').val();
			var max_elem = Math.min((page_index+1) * items_per_page, <?php echo @registry_count_all(); ?>);
			var newcontent = '<tr><th>Nº Registo</th><th>Nome</th><th>Data Pedido ABPSL</th>';
				newcontent += '<th>NIN</th><th>Data ROGD/LGM</th><th>Resolvido RNE</th><th>Nº LN</th><th>Nº LA</th>';
				newcontent += '<th>Finalizado pela ABPSL</th><th></th>';
			// Iterate through a selection of the content and build an HTML string

			for(var i=page_index*items_per_page;i<max_elem;i++)
			{
				newcontent += '<tr>';
					newcontent += '<td class="rightCell"><a class="link" href="'+'registry_show.php?id_registry=' + members[i][0] + '">'+ members[i][1] +'</a>'+'</td>';
					newcontent += '<td>' + members[i][2] + '</td>';
					newcontent += '<td>' + members[i][3] + '</td>';
					newcontent += '<td class="rightCell">' + members[i][4] + '</td>';
					newcontent += '<td>' + members[i][5] + '</td>';
					newcontent += '<td>' + members[i][6] + '</td>';
					newcontent += '<td class="rightCell">' + members[i][7] + '</td>';
					newcontent += '<td class="rightCell">' + members[i][8] + '</td>';
					newcontent += '<td>' + members[i][9] + '</td>';
					newcontent += '<td><a href="'+'registry_edit.php?id_registry=' + members[i][0] + '" class="edit">Editar </a>'+'<?php if(@is_admin()==1){ echo "| <a class=\"confirm\" data-cid=\"'+ members[i][0] + '\" href='+'#'+' >Eliminar</a>"; } ?></td>';
				newcontent += '</tr>';
				/*newcontent += '<dd class="state">' + members[i][2] + '</dd>';
				newcontent += '<dd class="party">' + members[i][3] + '</dd>';*/
			}
			// Replace old content with new content
			$('#Searchresult').html(newcontent);
			// Prevent click eventpropagation
			return false;
		}
		// The form contains fields for many pagiantion optiosn so you can
		// quickly see the resuluts of the different options.
		// This function creates an option object for the pagination function.
		// This will be be unnecessary in your application where you just set
		// the options once.
		function getOptionsFromForm(){
			var opt = {callback: pageselectCallback};
			// Collect options from the text fields - the fields are named like their option counterparts
			$("input:text").each(function(){
				opt[this.name] = this.className.match(/numeric/) ? parseInt(this.value) : this.value;
			});
			// Avoid html injections in this demo
			var htmlspecialchars ={ "&":"&", "<":"<", ">":">", '"':"""}
			$.each(htmlspecialchars, function(k,v){
				opt.prev_text = "Anterior";//opt.prev_text.replace(k,v);
				opt.next_text = "Seguinte"; //opt.next_text.replace(k,v);
			})
			return opt;
		}
		// When document has loaded, initialize pagination and form
		$(document).ready(function(){
			// Create pagination element with options from form
			var optInit = getOptionsFromForm();
			$("#Pagination").pagination(<?php echo @registry_count_all(); ?>, optInit);
			// Event Handler for for button
			$("#setoptions").click(function(){
				var opt = getOptionsFromForm();
				// Re-create pagination content with new parameters
				$("#Pagination").pagination(<?php echo @registry_count_all(); ?>, opt);
			});
		});
	</script>
<div id="site_content">
  <?php  include("sidebar/registry.php"); ?>
<h1 class="title">Lista de Registos</h1>
<div id="content">
  <a class="confirm" data-cid="275" href="#">Exemplo que funciona</a>
  <script>
 var id = false;
 $('.confirm').click(function(){
			 id = $(this).attr('data-cid');
			 $.showMessageBox({
							 content:"OK or close!",
							 title: 'Apagar Registo',
							 OkButtonDoneFunction: function() {
											$.post("includes/delete_registry.php?registry_id="+id);
							 },
							 type:'question'
			 });
 });
</script>
	  <div class="form_settings">
		<form name="search_form" action="registry_list.php" method="post">

			<input type="text" name="NinName" maxlength="150"  placeholder="Nome, NIN..." value="<?php echo $_SESSION['registry']; ?>" />

				<input class="submit" type="submit" name="search" value="Procurar"/>
				<input class="submit" type="submit" name="restart" value="Limpar" />

		</form>
	  </div>
		<div class="registos"><?php echo @registry_count_all(); ?> Registos</div>
		  <table style='width:100%; border-spacing:0;' id="Searchresult">

		  </table>
		   <div id="Pagination" class="pagination"> </div>
<div style="display:none;">					  
<label for="items_per_page">Number of items per page</label><input type="text" value="20" name="items_per_page" id="items_per_page" class="numeric"/>
<label for="num">Number of start and end points</label><input type="text" value="2" name="num_edge_entries" id="num_edge_entries" class="numeric"/>
</div>
</div>
<div class="clearFix"></div>
</div>

<?php require("includes/footer.php"); ?>
<?php include("includes/credits.php"); ?>

Share this post


Link to post
Share on other sites
yoda

Uma coisa que te vai ajudar imenso é separar os tipos de código. Mete o javascript num ficheiro à parte e incui-o no header do site.

Outra coisa que deves ter em conta : qualquer markup / html criado depois do site carregado (ou seja, pelo javascript ou algo similar) não vai pertencer ao DOM, logo as funções a elementos que logo após o inicial carregar da página nao existam, não vão ficar associadas. Por outras palavras, fazer $('.confirm').click(..); num elemento que é gerado depois do DOM inicial não vai funcionar, precisas fazer assim :

$('.confirm').on('click', function(){

ou, em versões mais antigas :

$('.confirm').delegate('click', function(){

Edited by yoda
  • Vote 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.