Sencillo y primitivo formulario de contacto

Email

He estado dándole una vuelta al formulario para que las librerías incorporadas (prototype y scriptaculous) cobraran un mayor protagonismo, dejando a PHP únicamente la función de enviar el email. Con esta nueva revisión, AJAX se encarga de la validación.

He querido incluir los efectos visuales de la librería Scriptaculous (Effect.Appear y Effect.Fade) de tal manera que el visitante debe ir cumplimentando el formulario para que los campos sucesivos vayan apareciendo. Como no estoy nada puesto aún envío la información al script PHP declarando un objeto AJAX (sé que estoy obviando el hecho de que con Prototype se hace más fácil) así que si alguien lo ve más fácil, le invito a que me lo diga; necesito consejos urgentemente ;)

Bueno, el código os lo pego aquí:

contacto.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 this script; 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/)

Icono: Proyecto TANGO (http://tango.freedesktop.org/Tango_Icon_Gallery)

*/

?>

<!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>Formulario de contacto</title>
<link href=”contacto.css” rel=”stylesheet” type=”text/css” />
<script src=”js/prototype.js” type=”text/javascript”></script>
<script src=”js/scriptaculous.js” type=”text/javascript”></script>
<script type=”text/javascript”>
function carga(){
new Effect.Appear(document.getElementById(‘nombre’));
Field.focus(‘txt_N’);
}
function valida_N(){
var nombre = $F(‘txt_N’);
if(nombre==”)
{
new Effect.Appear(document.getElementById(‘error’));
}
else
{
new Effect.Fade(document.getElementById(‘error’));
new Effect.Appear(document.getElementById(‘email’));
}
}
function valida_E(){
var email = $F(‘txt_E’);
if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,3})+$/.test(email))
{
new Effect.Fade(document.getElementById(‘error_mail’));
new Effect.Appear(document.getElementById(‘mensaje’));
}
else
{
new Effect.Appear(document.getElementById(‘error_mail’));
}
}
function valida_M(){
var mensaje = $F(‘area_mensaje’);
if(mensaje==”)
{
new Effect.Appear(document.getElementById(‘error’));
}
else
{
new Effect.Fade(document.getElementById(‘error’));
new Effect.Appear(document.getElementById(‘envia’));
}
}
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 envia(){
var nombre = $F(‘txt_N’);
var email = $F(‘txt_E’);
var mensaje = $F(‘area_mensaje’);
divResultado = document.getElementById(‘resultado’);

ajax=objetoAjax();

ajax.open(‘POST’, ‘envia.php’,true);

ajax.onreadystatechange=function()
{

if (ajax.readyState==4)
{

divResultado.innerHTML = ajax.responseText

}

}

ajax.setRequestHeader(‘Content-Type’,'application/x-www-form-urlencoded’);
if(nombre != ” && mensaje != ” && /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,3})+$/.test(email))
{

ajax.send(‘nombre=’+nombre+’&email=’+email+’&mensaje=’+mensaje);
}
else
{
new Effect.Appear(document.getElementById(‘error’));
}
}
</script>
</head>
<body onload=”carga()”>
<div id=”contenido”>
<form name=”formulario” id=”formulario”>

<p style=”display:none” id=”nombre”>
Nombre: <input id=”txt_N” name=”txt_N” type=”text” size=”30″ onkeydown=”valida_N()” />
</p>

<p style=”display:none” id=”email”>
Email: <input id=”txt_E” name=”txt_E” type=”text” size=”30″ onkeydown=”valida_E()” />
</p>

<p style=”display:none” id=”mensaje”>
Tu mensaje
<br><br>
<textarea cols=”50″ rows=”10″ id=”area_mensaje” name=”area_mensaje” onkeydown=”valida_M()”></textarea>
</p>

<p style=”display:none” id=”envia”>
<a href=”#” title=”Enviar Mensaje” onclick=”envia()”><img src=”images/enviar.png” alt=”Enviar”/></a>
</p>

<p style=”display:none;background-color:red;” id=”error”>
El campo no puede estar vacío. Por favor, introduce el dato solicitado
</p>

<p style=”display:none;background-color:red;” id=”error_mail”>
Debes introducir una dirección de correo válida
</p>

</form>
</div>

<div id=”resultado”>
</div>

<div id=”fondo”>
<a href=”http://ramoncastro.es” title=”La web de Ramón Castro”><img src=”http://ramoncastro.es/wp-content/themes/minid/images/logotipo.png” alt=”La web de Ramón Castro”/></a>
</div>

</body>
</html>
envia.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 this script; 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/)

Icono: Proyecto TANGO (http://tango.freedesktop.org/Tango_Icon_Gallery)

*/

$nombre = $_POST['nombre'];
$email = $_POST['email'];
$mensaje = $_POST['mensaje'];

$mail = ‘ramoncastroperez@yahoo.es’;
$asunto = ‘Mensaje de la web’;
$momento = date(‘d/m/y H:i a’);
$contenido = ”.$nombre.’, con mail ‘.$email.’ ha enviado el ‘.$momento.’ el siguiente mensaje:

‘.$mensaje.”;

//avisamos
echo ‘<div id=”resultado”>’;
if(mail($mail,$asunto,$contenido))
{
$aviso = ‘Tu mensaje ha sido enviado. Gracias’;
echo $aviso;
}
else
{
$aviso = ‘Tu mensaje no ha podido ser enviado. Inténtalo más tarde. Gracias’;
echo $aviso;
}

?>
Como véis, no he añadido nada nuevo al script PHP que envía el mail (queda pendiente: cambiar la codificación de la información, que llega al mail con las tildes diabólicas, incorporar información sobre el navegador, SO e IP).

Podéis ver el ejemplo en mi web, aquí.

Saludos


About this entry