Last active
August 29, 2015 14:06
-
-
Save TICLasPalmas/9e79479f611bd502c63c to your computer and use it in GitHub Desktop.
Enviar formularios con AJAX y jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Esperamos a que la web haya cargado | |
$(document).ready(function(){ | |
// Evento activado tras hacer click en el botón Enviar del | |
// formulario cuya id es "submit-form" | |
$("#submit-form").click(function(evento){ | |
// Eliminamos el comportamiento por defecto del form | |
// para que no se ejecute el action del formulario | |
evento.preventDefault(); | |
// Cargamos el resultado que nos envía el archivo sendmail.php | |
// en la etiqueta #respuesta de formulario.html tras enviarle | |
// los parametros por POST | |
$("#respuesta").load("sendform.php", { | |
// Asignamos a una variable $_POST["mensaje_post"] el | |
// contenido del cuadro de texto cuya id es "mensaje" | |
mensaje_post: $("#mensaje").val() | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<!-- Título de la página --> | |
<title>Formulario</title> | |
<!-- Importamos la librería jQuery --> | |
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script> | |
<!-- Importamos nuestro gestor de llamada asíncrona --> | |
<script type="text/javascript" src="async_form.js"></script> | |
</head> | |
<body> | |
<!-- Formulario simple --> | |
<form name="formulario" method="post"> | |
<!-- Área de texto --> | |
<textarea id="mensaje" name="mensaje"></textarea> | |
<!-- Botón para enviar el formulario --> | |
<input id="submit-form" type="submit" value="Enviar"> | |
</form> | |
<!-- lugar donde se mostrarán las respuestas de sendform.php --> | |
<span id="respuesta"></span> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Si el cuadro de texto contiene algo lo mostramos | |
if ($_POST["mensaje_post"] != "") { | |
// Imprimimos la variable POST recibida mediante la llamada | |
// asíncrona con jQuery | |
echo $_POST["mensaje_post"]; | |
// Si no escribimos nada en el mensaje, mostramos el | |
// siguiente texto | |
} else { | |
echo "Introduzca un mensaje."; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment