views:

701

answers:

1

Hi everyone,

I'm some kind of lost with the way i have to deal with Javascript, JSON and Perl and most of the examples are in PHP which is not helpfull for me.

I have a page (called main.html) where i have a with data from MySQL and i have an option to delete a row by id.

Then i have the Javascript sending the id to page apagar.html which is some kind mess now cos i was trying to deal with JSON, but with GET it works, and what is missing is a refresh after the delete request. But i wanted to introduce JSON in my code and make the page more dinamic but don't know how.

And in my apagar.html i have only the code to delete if there is any id in the url.

I have read the IBM Series (Mastering Ajax) : http://www.ibm.com/developerworks/web/library/wa-ajaxintro11.html?S%5FTACT=105AGX08&S%5FCMP=EDU

Thank you for your help, above is the javascript i'm using:

<script language="javascript" type="text/javascript">
  var pedido = false; // pedido = request

  try {
     pedido = new XMLHttpRequest();
  }
    catch (failed) {
       pedido = false
    }

  if (!pedido) {
     alert("O seu browser não é suportado."); // Browser not supported
  }

   function Eliminar(rid) { // relativo a main.html & apagar.html
      //alert("SK"); //debug
      if ( confirm("Deseja realmente eliminar?") ) {
       var url = "/back/apagar.html?rid=" + escape(rid);
       /*POST*/
       pedido.open("POST", url, true);
       pedido.onreadystatechange = updatePage;
       pedido.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

       pedido.send( contacto.toJSONString() );
       //pedido.open("GET", url, true);
       //pedido.send(null);

      }
      return false;
   }

AND the Mason apagar.html page

<%args>
$rid => ''
</%args>

<%once>
use lib '/var/www/projectox/';
use db::Conexao; #interacao com a DB
use DBI;
use Apache2::Cookie; #interacao com cookies
</%once>

<%init>
% # vê se existem cookies
my $cookies = Apache2::Cookie->fetch($r);
 if(!$cookies){ #sem cookies é enviado para o login
  $m->redirect('login.html');
 }

 if($rid) {
  # vai eliminar os dados pelo valor do id ($rid)

  #ligacao à DB
  my $tomada = db::Conexao->Conexao();

  my $sql = $tomada->prepare("Delete from Contactos where id=?") ||
    die "Impossivel de realizar a operação: $!";

 $sql->execute($rid) || die "Não foi possivel executar: $!";

 #desliga da DB
 $tomada->disconnect || warn "Não foi possivel terminar a ligação!";

</%init>
+1  A: 

Hi again, sorry for making you guys lost your time. I finally resolved my issue:

In my Javascript (using JQuery) i've done:

$(document).ready(function() {
// relativo ao main.html
$("#over_tabela tr").mouseover( function() {
 $(this).addClass("sobre_linha");
}).mouseout( function() {
 $(this).removeClass("sobre_linha");
});

    // this is to "delete" the row from the table of main.html file throw ajax and JSON
$('a.delete_link').click(function(e){
  e.preventDefault();
  if(confirm('Tem a certeza?')){
   url = $(this).attr('href');
   $.ajax({
    type: "GET",
    url: url,
    dataType: "json",
    success: function(msg){
     $('#linha_'+ msg.id).hide("slow");
    }
    });
  }
 });

});

Then in my apagar.html :

<%args>
$rid => ''
</%args>

<%once>
use lib '/var/www/projectox/';
use db::Conexao;    # module that interact with database
use DBI;
use Apache2::Cookie;    #cookies, not the right way, gonna update to Session Cookies
</%once>

<%init>
# vê se existem cookies
my $cookies = Apache2::Cookie->fetch($r);
    if(!$cookies) { #sem cookies é enviado para o login
     $m->redirect('login.html');
    }

 if($rid) {
  # vai eliminar os dados pelo valor do id ($rid)

  #database connection
  my $tomada = db::Conexao->Conexao();

  my $sql = $tomada->prepare("Delete from Contactos where id=?") ||
     die "Impossivel de realizar a operação: $!";

    $sql->execute($rid) || die "Não foi possivel executar: $!"; # execute or die with a message

    #disconnect from database or warn about problem
    $tomada->disconnect || warn "Não foi possivel terminar a ligação!";

    print qq{ { id : $rid } }; #JSON style, this was what made me go crazy... lol and in the end was soooooo easy as that
  }
</%init>

and finally in my main.html:

    <%args>
$sair => 0
</%args>

<%once>

use lib '/var/www/projectox/';
use db::Conexao;
use DBI;
use Apache2::Cookie;
</%once>

<%init>
# vê se existem cookies
my $cookies = Apache2::Cookie->fetch($r);
    if(!$cookies){ #without cookies user is redirect to login.html
     $m->redirect('login.html');
    }

    if($sair){ # if he logout : cookie expire and user is sent to index.html
    my $cookie = Apache2::Cookie->new($r,
     -name => "CHOCO",
     -value => "TWIX",
     -expires=> '+0s'
     );
     $cookie->bake($r);
     $m->redirect('../index.html');
    }


    my $tomada = db::Conexao->Conexao(); 

    my $sql = $tomada->prepare("Select * from Contactos") ||  # select all from table Contactos or die..
     die "Impossivel : $!";

    $sql->execute() || die "Nao foi possivel executar: $!";

Generate HTML here

    print qq{
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" lang="pt" xml:lang="pt">
<head>
    <meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="../shadowbox/shadowbox.css">
    <link rel="stylesheet" href="../css/estilo.css" type="text/css" />

    <script language="javascript" src="../js/jquery.js"></script>
    <script language="javascript" src="../js/wii.js"></script>

    <script type="text/javascript" src="../shadowbox/shadowbox.js"></script>

    <script type="text/javascript">
    Shadowbox.init({
     language:   "pt-PT",
     players:    ["html","iframe","qt"],
     viewportPadding: 30,
     overlayOpacity:  0.9,
     overlayColor: "#9999ff"
    });
    </script>
</head>
<body>
    <form id="logout" name="logout" action="" method="post" >
     <p>
      <input type="submit" id="sair" name="sair" value="Sair" />
     </p>
    </form>
    Bem Vindo #USERNAME !
    <table id="over_tabela" name="over_tabela" align="center" border="0" cellspacing="1" cellpadding="5">
    <thead>  
      <tr>
       <th>NOME</th><th>E-MAIL</th><th>MENSAGEM</th><th>OP&Ccedil;&Atilde;O</th>
      </tr>
    </thead>
     };

    my @dados; # receive data from database
    my $dados; # part of @dados, id -> $dados[0]; nome -> $dados[1] etc..

    while ( @dados = $sql->fetchrow_array() ) { #data is sent in html table form
     print qq{
     <tbody>
      <tr id="linha_$dados[0]">
       <td>$dados[1]</td><td>$dados[2]</td><td>$dados[3]</td>
       <td>
        <a class="edit_link" href="/back/editar.html?rid=$dados[0]" rel="shadowbox;width=440;height=320">
         <img src="../imagens/editar.png" width="24" height="24" border="0" title="Editar" />
        </a>
        &nbsp;
        <a class="delete_link" href="/back/apagar.html?rid=$dados[0]">
         <img src="../imagens/eliminar.png" width="24" height="24" border="0" title="Apagar" />
        </a>
       </td>

      </tr>
     </tbody>
     };
    }
    print qq {</table>
</body>
</html>}; #end of HTML

    #disconnect from database
    $tomada->disconnect || warn "Não foi possivel terminar a ligação: $!";
</%init>
Davidslv
Perhaps you could summarize the big code dumps so we know what you did by reading a couple of sentences :)
brian d foy
Hi brian d foy, yes i could, but then i see a problem, when someone come and see the code it will not see a code that work. And i hate when something isn't complete. What i agree is to change my portuguese comments to english.
Davidslv