Aligerando la web con AJAX (de fondo, sin hacer ruido)

Sin hacer ruido

No sé casi nada de AJAX pero algún día habrá que empezar y qué mejor fuente que Ribosomatic, con tantos ejemplos. Aquí os pongo uno facilito que he adaptado para comprobar lo bien que se trabaja con esta tecnología.

Haremos lo siguiente:

- LLegamos a una página donde tenemos seleccionados a un@s alumn@s
- Hacemos clic sobre su nombre y se nos presenta la nota
- Todo esto tiene lugar sin recarga de la página
- En el ejemplo todo está en la misma tabla pero puede hacerse lo complicado que uno quiera

Entran en juego:

- index.php que nos presenta el listado de alumn@s, los enlaces con una función que al clicarlo llamará al script mira_nota.php. Además, index.php contiene un elemento [div] vacío que albergará el resultado

- funciones.js que inicializa el objeto XMLHttpRequest y que contiene la función pedirDatos(codigo) que llama a mira_nota.php para que extraiga de la base de datos la calificación del código pasado. Una vez tenga el resultado, lo lleva al [div] vacío de index.php. Todo esto tiene lugar en la trastienda, sin recarga de página

- mira_nota.php que se encarga de consultar a la base de datos la calificación y listarla

- index.css que es responsable de los estilos

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)

Iconos: Proyecto Tango (http://tango.freedesktop.org/Tango_Desktop_Project)

Fuente código: Ribosomatic (http://www.ribosomatic.com/ejemplos/pagina/5/)

*/

?>

<!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>Principal</title>
<link href=”index.css” rel=”stylesheet” type=”text/css” />
<script type=”text/javascript” src=”funciones.js”></script>
</head>
<body>
<div id=”encabezado”>Web de Prueba</div>

<?php

//conectamos con mysql y con la base de 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’);

//realizamos la consulta

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

//presentamos el elemento <div> donde irá la lista

echo ‘<div id=”contenido”>’;
//el formulario
echo ‘<form name=”formulario”>’;
echo ‘<ul>’;
echo ‘</li>ALUMN@</li>’;
echo ‘<br />’;
echo ‘<br />’;

//montamos el bucle

for($a=0;$a<(mysql_num_rows($select));$a++)
{
//extraemos el registro completo
$registro = mysql_fetch_array($select);
/*extraemos los valores y los presentamos
en la lista. El nombre es un enlace que
al pulsar hará que la aplicación nos
muestre la calificación obtenida*/
$codigo = $registro['codigo'];
echo ‘<li><a href=”#” onclick=”pedirDatos(\”.$codigo.’\')” title=”Ver nota”>’.$registro['alum'].’</a></li>’;
}//fin de bucle
//cerramos lista, formulario y <div>
echo ‘</ul>’;
echo ‘</form>’;
echo ‘</div>’;

//presentamos el <div> donde aparecerá la nota

echo ‘<div id=”resultado”></div>’;

?>

</body>
</html>

funciones.js


//Desarrollado por Jesus Liñán
//webmaster@ribosomatic.com

//ribosomatic.com

//Puedes hacer lo que quieras con el código

//pero visita la web cuando te acuerdes

function objetoAjax(){

var xmlhttp=false;

try {

xmlhttp = new ActiveXObject(“Msxml2.XMLHTTP”);

} catch (e) {

try {

xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);

} catch (E) {

xmlhttp = false;

}

}

if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {

xmlhttp = new XMLHttpRequest();

}

return xmlhttp;

}

function pedirDatos(codigo){

//donde se mostrará el resultado

divResultado = document.getElementById(‘resultado’);

//tomamos el valor de la lista desplegable

var codigo;

//instanciamos el objetoAjax

ajax=objetoAjax();

//usamos el medoto POST

//archivo que realizará la operacion

//datoscliente.php

ajax.open(“POST”, “mira_nota.php”,true);

ajax.onreadystatechange=function() {

if (ajax.readyState==4) {

//mostrar resultados en esta capa

divResultado.innerHTML = ajax.responseText

}

}

ajax.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”);

//enviando los valores

ajax.send(“codigo=”+codigo)

}
mira_nota.php


<?php
//recogemos variable POST
$codigo = $_POST['codigo'];
//si lo tenemos, seguimos:
if($codigo)
{

//conectamos con mysql y con la base de 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’);
//consultamos
$select = mysql_query(“select * from notas where codigo=’$codigo’”);

//presentamos
$registro = mysql_fetch_array($select);
$alum = $registro['alum'];
$nota = $registro['nota'];
echo ‘<br />’;
echo ‘<br />’;
echo $alum;
echo ‘ ‘;
echo $nota;

}
else
{
echo ‘Ha ocurrido un error’;
}

?>
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)

Iconos: Proyecto Tango (http://tango.freedesktop.org/Tango_Desktop_Project)

*/
*{
margin:0;

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

body{

font-family: Andale Mono;

font-size:12px;
text-align:left
}

div#encabezado{
font-size:44px;
height:70px;
border-bottom: 1px solid #444;
padding:30px;
background:transparent url(../imgs/encab.png) no-repeat center bottom;
text-align:center;
}

div#contenido{
position:absolute;
top:250px;
left: 200px;
width:200px;
}

div#resultado{
text-align:center;
position: absolute;
font-size:30px;
top:250px;
left:400px;
width:500px;
background:transparent url(../imgs/not.png) no-repeat center top;
}

Saludos

[tag]ajax, php, consulta[/tag]


About this entry