Tutorial Sencillo formulario de contacto

Estado
No está abierto para más respuestas.
K

kanikase

Invitado
Hola veintes :v andaba aburrido así que me decidí a hacer este tutorial para este foro, es un sencillo pero bonito y funcional formulario de contacto en php, y ajax, no hablaré demasiado, sólo pondré los códigos, los archivos y eso, lo demás ya deben saberlo hacer :sisi1: así que empecemos:

Archivos necesarios:
  1. index.html (donde estará el from).
  2. ajax.js
  3. style.css
  4. enviaMail.php

index.html:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Enviar Email</title>
	<script type="text/javascript" src="//code.jquery.com/jquery-latest.min.js"></script>
	<script type="text/javascript" src="ajax.js"></script>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<form id="contactForm">
		<label for="email">Email:</label>
		<input type="email" id="email" name="email" placeholder="Escribe tu correo.">
		<label for="nombre">Nombre:</label>
		<input type="text" id="nombre" name="nombre" placeholder="Escribe tu nombre.">
		<label for="asunto">Asunto:</label>
		<input type="text" id="asunto" name="asunto" placeholder="El asunto del correo">
		<label for="descripcion">Descripción:</label>
		<span class="caracteres">500</span>
		<textarea name="descripcion" id="descripcion" cols="30" rows="10" placeholder="Escribe una descripción del problema"></textarea>
		<div id="comprueba">
			<p>Comprueba que no eres un robot: </p>
			<input type="text" id="n1" name="n1" readonly> + <input type="text" id="n2" name="n2" readonly>
			=
			<input type="text" id="res" name="res" maxlength="2">
		</div>
		<input type="submit" id="enviar" value="Enviar">
		<div style="clear:both"></div>
		<div id="respuesta"></div>
	</form>
</body>
</html>

style.css:
Código:
#contactForm {
	width: 500px;
}
#contactForm * {
	font-family: sans-serif;
	display: block;
	box-sizing: border-box;
}
#contactForm label {
	color: #333;
	cursor: default;
	margin: 15px 0 3px 0;
}
#contactForm input[type="text"], #contactForm input[type="email"], #contactForm textarea {
	padding: 8px;
	border: 1px solid #CCC;
	color: #555;
	font-size: 1em;
	width: 100%;
	overflow: hidden;
	resize: none;
	border-radius: 3px;
	-o-border-radius: 3px;
	-ms-border-radius: 3px;
	-moz-border-radius: 3px;
}
#contactForm input[type="text"]:focus, #contactForm input[type="email"]:focus, #contactForm textarea:focus {
	outline: none;
	box-shadow: 0px 0px 5px #007DD7;
	-o-box-shadow: 0px 0px 5px #007DD7;
	-ms-box-shadow: 0px 0px 5px #007DD7;
	-moz-box-shadow: 0px 0px 5px #007DD7;
}
#contactForm .caracteres, #contactForm label[for="descripcion"] {
	display: inline-block;
}
#contactForm .caracteres {
	color: green;
}
#contactForm #comprueba {
	margin: 10px 0;
	float: left;
}
#contactForm #comprueba p {
	display: inline-block;
	color: #333;
	margin: 0;
}
#contactForm #comprueba #n1, #contactForm #comprueba #n2 {
	display: inline-block;
	width: 20px !important;
	border: none !important;
	padding: 0 !important;
	margin: 0;
	text-align: center;
}
#contactForm #comprueba #n1:focus, #contactForm #comprueba #n2:focus {
	box-shadow: none;
	-o-box-shadow: none;
	-ms-box-shadow: none;
	-moz-box-shadow: none;
}
#contactForm #comprueba #res {
	display: inline-block;
	width: 25px;
	padding: 2px;
}
#contactForm #comprueba #res:focus {
	box-shadow: none;
	-o-box-shadow: none;
	-ms-box-shadow: none;
	-moz-box-shadow: none;
}
#contactForm #enviar {
	border: 1px solid #0169A9;
	cursor: pointer;
	float: right;
	background: linear-gradient(#08A1FF,#008DE4,#0275BB);
	-o-background: linear-gradient(#08A1FF,#008DE4,#0275BB);
	-ms-background: linear-gradient(#08A1FF,#008DE4,#0275BB);
	-moz-background: linear-gradient(#08A1FF,#008DE4,#0275BB);
	color: #FFF;
	font-size: 1em;
	margin: 10px 0 10px 15px;
	padding: 3px 9px;
	border-radius: 2px;
	-o-border-radius: 2px;
	-ms-border-radius: 2px;
	-moz-border-radius: 2px;
}
#contactForm #enviar:hover {
	background: linear-gradient(#0275BB,#008DE4,#08A1FF);
	-o-background: linear-gradient(#0275BB,#008DE4,#08A1FF);
	-ms-background: linear-gradient(#0275BB,#008DE4,#08A1FF);
	-moz-background: linear-gradient(#0275BB,#008DE4,#08A1FF);
}
#contactForm #enviar[disabled] {
	background: linear-gradient(#08A1FF,#008DE4,#0275BB);
	-o-background: linear-gradient(#08A1FF,#008DE4,#0275BB);
	-ms-background: linear-gradient(#08A1FF,#008DE4,#0275BB);
	-moz-background: linear-gradient(#08A1FF,#008DE4,#0275BB);
	filter: alpha(opacity=60);
	opacity: 0.6;
	cursor: default;
}
#contactForm #respuesta {
	display: none;
	padding: 6px;
	background: #008DE4;
	color: #FFF;
	text-align: center;
	margin: 10px 0;
	border: 1px solid #0076BE;
	cursor: pointer;
	border-radius: 2px;
	-o-border-radius: 2px;
	-ms-border-radius: 2px;
	-moz-border-radius: 2px;
}

ajax.js:
Código:
$(document).ready(function() {
	$('#n1').val(Math.floor(Math.random()*10+1));
	$('#n2').val(Math.floor(Math.random()*10+1));
	$('#contactForm').submit(function(event) {
		$('#respuesta').fadeOut(250);
		$.ajax({
			url: 'enviaMail.php',
			type: 'POST',
			data: $(this).serialize(),
			success: function(resp) {
				$.each($('#respuesta'), function(event) {
					$(this).fadeIn(250);
					$(this).html(resp);
					if ($(this).html() == $('#nombre').val()+', ha enviado el correo de forma exitosa.') {
						$.each($('#enviar'), function(event) {
							$(this).attr({
								disabled : true,
								value : 'Enviado'
							});
							$(this).click(function() {
								return false;
							});
						});
					}
				});
			},
			error: function(jqXHR, textStatus, errorThrown) {
				$.each($('#respuesta'), function(event) {
					$(this).fadeIn(250);
					$(this).html('Error, no se ha podido enviar el correo, inténtelo más tarde');
				});
			}
		});
		return false;
	});
	$('#descripcion').keyup(function(event) {
		$('.caracteres').text(500 - $(this).val().length);
		if ($(this).val().length > 500) {
			$('.caracteres').css('color','red');
			$('#enviar').attr('disabled',true);
		} else {
			$('.caracteres').css('color','green');
			$('#enviar').attr('disabled',false);
		}
	});
	$('#n1, #n2').keydown(function() {
		return false;
	});
	$('#respuesta').click(function(event) {
		$(this).fadeOut(250);
	});
});

enviaMail.php:
PHP:
<?php
error_reporting(0);
// A donde se enviará el correo
$correo = "AQUÍ TU CORREO";
// Para poder envíar html en el mensaje
$cabecera  = "MIME-Version: 1.0"."\r\n";
$cabecera .= "Content-type: text/html; charset=UTF-8"."\r\n";
// Datos del correo, como el email, nombre asunto y el cuerpo del correo, y de la verficación de números
$email = htmlentities($_POST["email"]);
$nombre = htmlentities($_POST["nombre"]);
$asunto = htmlentities($_POST["asunto"]);
$desc = str_replace("\n", "<br>", $_POST["descripcion"]);
$respuesta = $_POST["res"];
$n1 = $_POST["n1"];
$n2 = $_POST["n2"];
$respuesta1 = $n1+$n2;
// Verificamos que todos los campos esten llenos
if ($email == null || $nombre == null || $asunto == null || $desc == null || $respuesta == null) {
	// Si los campos no están llenos, terminamos el proceso y mostramos el error.
	die("Error, tienes que completar todos los campos.");
}
// Comprobamos que es humano
if ($respuesta != $respuesta1) {
	// Si no es correcta la operación terminamos el proceso y mostramos el error.
	die("Error, haz que la suma de el número correcto.");
}
if (mail($correo, $asunto, "<b>Nombre</b>: ".$nombre."<br><b>Correo</b>: ".$email."<br><b>Problema</b>: ".$desc, $cabecera)) {
	// Si el correo se envia terminamos el proceso y mostramos el mensaje.
	die($nombre.", ha enviado el correo de forma exitosa.");
}
// Cualquier otro error, mostramos un mensaje de error.
echo "Error, no se ha podido enviar el correo, inténtelo más tarde.";
?>

Y LISTO XD DEMO
 

Suado

Suspendido
Mensajes
53
Puntuación de reacción
0
Muchas gracias por el aporte, voy a probarlo y te comento
 
Estado
No está abierto para más respuestas.
Arriba