Edición en línea (ya sabes: AJAX y … del lado del servidor, PHP)

Editor

Poco a poco voy escrutando las extraordinarias librerías de Script.aculo.us. Le toca ahora a la edición en línea (tema que aprovecha mucho mejor Mario Debian con su Inline Editor trabajado sobre éstas), sin duda uno de las técnicas que mejores resultados pueden darnos si detrás del formulario contamos con una base de datos y un intérprete (PHP, por ejemplo).

Así que me he puesto a seguir la documentación del wiki y ¡funciona!, así que os pego aquí el código.

Archivos:

- index.php –> Muestra una tabla con datos sobre empleados obtenida al consultar una base de datos usando para ello un bucle for. Las celdas que serán editables están identificadas con un nombre corto más el valor de la iteración corriente. Al final de la página llamamos a la librería script.aculo.us para que, al hacer clic en el contenido, convierta la celda en un cuadro de texto (hay muchas más opciones, digno de mirar en la documentación) y aparezca un botón tipo “submit” para enviar la orden (sin necesidad de recarga de la página: esto es AJAX) al script:

- guarda.php –> Recibe el valor de cada iteración y si la variable no está vacía (es decir, hemos editado y enviado) actualiza el registro en la base de datos y lo muestra. Así de sencillo.

- index.css –> Se encarga de los estilos

Las posibilidades son amplias: cajas de texto, áreas de texto, select, etcétera …

El código:

index.php


<?php
/*
This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
You cand find a copy of the GNU General Public License in the “license” directory.

You should have received a copy of the GNU General Public License along with SIESTTA; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.

Ramon Castro (http://ramoncastro.es)

Uso de librerías AJAX:

Prototype -> (http://www.prototypejs.org/)

Script.aculo.us -> (http://script.aculo.us/)

*/

?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Editando en línea con AJAX</title>
<link href=”index.css” rel=”stylesheet” type=”text/css” />
<script src=”js/prototype.js” type=”text/javascript”></script>
<script src=”js/scriptaculous.js” type=”text/javascript”></script>
</head>
<body>

<?php

//presentamos título

echo ‘<h1>Emplead@s de la empresa</h1>’;

//presentamos caja

echo ‘<div id=”caja”>’;
echo ‘<b class=”rtop”><b class=”r1″></b><b class=”r2″></b><b class=”r3″></b><b class=”r4″></b></b>’;

//la tabla

echo ‘<table>’;

echo ‘<tr id=”encab”>’;
echo ‘<td>Id</td>’;
echo ‘<td>Emplead@</td>’;
echo ‘<td>Cargo</td>’;
echo ‘</tr>’;

//conectamos con mysql y seleccionamos los datos

$con_mysql=mysql_connect(‘localhost’,’scripts’,’scripts’);

if (!$con_mysql) {echo ‘No se ha podido encontrar el servidor de datos’;exit;}

mysql_select_db(’scripts’);

$select = mysql_query(“select * from empleados”);

//montamos bucle

for($a = 0; $a < (mysql_num_rows($select)); $a++)

{
$reg = mysql_fetch_array($select);
echo ‘<tr>’;
echo ‘<td>’;
echo $reg['id'];
echo ‘</td>’;
echo ‘<td><p id=”emp-’.$a.’”>’;
echo $reg['empleado'];
echo ‘</p></td>’;

echo ‘<td><p id=”car-’.$a.’”>’;
echo $reg['cargo'];
echo ‘</p></td>’;
echo ‘</tr>’;
echo ‘
<script type=”text/javascript”>
new Ajax.InPlaceEditor(\’emp-’.$a.’\', \’guarda.php\’,{method: \’post\’, paramName: \’emp-’.$a.’\', size:\’15\’});
</script>
‘;
echo ‘
<script type=”text/javascript”>
new Ajax.InPlaceEditor(\’car-’.$a.’\', \’guarda.php\’,{method: \’post\’, paramName: \’car-’.$a.’\', size:\’15\’});
</script>
‘;

}

echo ‘<table>’;

echo ‘<b class=”rbottom”><b class=”r4″></b><b class=”r3″></b><b class=”r2″></b><b class=”r1″></b></b>’;
echo ‘</div>’;

?>

</body>
</html>

guarda.php


<?php
/*
This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

You cand find a copy of the GNU General Public License in the “license” directory.

You should have received a copy of the GNU General Public License along with SIESTTA; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.

Ramon Castro (http://ramoncastro.es)

Uso de librerías AJAX:

Prototype -> (http://www.prototypejs.org/)

Script.aculo.us -> (http://script.aculo.us/)

*/

//conectamos con mysql, cargamos variables y actualizamos

$con_mysql=mysql_connect(‘localhost’,’scripts’,’scripts’);

if (!$con_mysql) {echo ‘No se ha podido encontrar el servidor de datos’;exit;}

mysql_select_db(’scripts’);

$select = mysql_query(“select * from empleados”);

for($a=0;$a<(mysql_num_rows($select));$a++)

{
$reg = mysql_fetch_array($select);
$id = $reg['id'];
$emp = $_POST['emp-'.$a.''];
$car = $_POST['car-'.$a.''];

//si se cambia empleado actualizamos
if(isset($emp))
{
$update = mysql_query(“update empleados set empleado=’$emp’ where id=’$id’”);
//muestro el texto
echo $emp;
}
//si se cambia empleado actualizamos
if(isset($car))
{
$id = $reg['id'];
$update = mysql_query(“update empleados set cargo=’$car’ where id=’$id’”);
//muestro el texto
echo $car;
}

}

?>

index.css


/*
This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
You cand find a copy of the GNU General Public License in the “license” directory.

You should have received a copy of the GNU General Public License along with SIESTTA; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.

Ramon Castro (http://ramoncastro.es)

*/

*{
margin:0;

padding:0;
}
a {text-decoration:none;}
a:link, a:visited{color:#444;}
a:hover, a:active{color:white;}
input{
border:1px solid #444;
margin:4px;
font-size:10px;
}
input:hover{
border:1px solid #0021a5;
}

body{

font-family: Andale Mono;

font-size:12px;
}
h1{
position:relative;
text-align:center;
background:transparent;
top:110px;
width:40%;
height:20px;
margin:auto;
}
div#caja{
position:relative;
margin:auto;
width:50%;
top:150px;
background:#199eee;
}
#caja table{
margin:auto;
padding: 20px;
}
#caja table tr#encab{
font-weight:bold;
text-align:center;
background:white;
}
#caja table td{
padding:4px;
}
b.rtop, b.rbottom{
display:block;
background: #FFF;
}
b.rtop b, b.rbottom b{
display:block;
height: 1px;
overflow: hidden;
background: #199eee;
}
b.r1{
margin: 0 5px
}
b.r2{
margin: 0 3px;
}
b.r3{
margin: 0 2px;
}
b.rtop b.r4, b.rbottom b.r4{
margin: 0 1px;
height: 2px;
}
.inplaceeditor-saving { background: url(../imgs/spinner.gif) bottom right no-repeat; }

Saludos

[tag]ajax, editor, php[/tag]



Acerca de esta Entrada