Ejemplo básico de JQuery y Ajax

Posted: enero 28, 2011 in jQuery AJAX, Tecnología

Este ejemplo trata algunos aspectos básicos sobre jQuery y AJAX. Se construirá un formulario AJAX con un campo. Si se deja en blanco el campo y ejecutamos el formulario, se obtiene un mensaje de error. Si llenamos con algún dato se obtiene el texto digitado. Se adicionarán algunas imagenes de carga.

Primero que todo la estructura de archivos.

Estructura de Archivos

Estructura de Archivos

El archivo index.php

<!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=utf-8" />
        <title>Ajax submit</title>
        <link href="css/main.css" type="text/css" media="screen, projection" rel="stylesheet" />
        <script type="text/javascript" src="js/jquery/jquery-1.3.2.js"></script>
    </head>
  <script type="text/javascript">

function sendAjax(path, data, successFunction)
{
    $.ajax({
		type : 'POST',
		url : 'post.php',
		dataType : 'json',
		data: data,
		success : featureAdd,
		error : showError
    });
}

function showError(XMLHttpRequest, textStatus, errorThrown) {
		$('#waiting').hide(500);
		$('#message').removeClass().addClass('error')
		.text('There was an hp error, nunca ha salido.').show(500);
		$('#demoForm').show(500);
}
</script>

<body>
        <div id="wrapper">
            <div id="message" style="display: none;">
            </div>
            <div id="waiting" style="display: none;">
                Please wait<br />
                <img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
            </div>
            <form action="" id="demoForm" method="post">
                <fieldset>
                    <legend>Demo form</legend>
                    <span style="font-size: 0.9em;">This ajax submit demo form.</span>
                    <p>
                        <label for="email">E-Mail:</label>
                        <input type="text" name="email" id="email" value="" />
                    </p>
                    <p>
                        <a name="submit" id="submit" style="float: right; clear: both; margin-right: 3px;" value="Submit"  onclick="clkLi(this)">dd </a>
                    </p>
                </fieldset>
            </form>
        </div>

<script type="text/javascript" >

function clkLi(th)
{
		$('#waiting').show(20);
		$('#demoForm').hide(0);
		$('#message').hide(0);

		sendAjax('post.php', {email: $('#email').val()}, featureAdd)
		return false;
}

function featureAdd(data)
{
		$('#waiting').hide(20);
		$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
			.text(data.msg).show(500);
		if (data.error === true) //para mostrar de nuevo el formulario
		$('#demoForm').show(500);
}
</script>

</body>
</html>

El archivo main.css

@CHARSET "UTF-8";
body {
    background-color: #f0f0f0;
}

#wrapper {
    margin: 100px auto;
    width: 310px;
}

#email {
    width: 248px;
}

#text {
    width: 248px;
    height: 70px;
}

#waiting {
    color: #767676;
    text-align: center;
}

fieldset {
    margin-top: 10px;
    background: #fff;
    border: 1px solid #c8c8c8;
    background-color: #fff;
}

legend {
    background-color: #fff;
    border-top: 1px solid #c8c8c8;
    border-right: 1px solid #c8c8c8;
    border-left: 1px solid #c8c8c8;
    font-size: 1.2em;
    padding: 0px 7px;
}

label {
    display: inline-block;
    width: 50px;
}

.success {
    width: 298px;
    background: #a5e283;
    border: #337f09 1px solid;
    padding: 5px;
}

.error {
    width: 298px;
    background: #ea7e7e;
    border: #a71010 1px solid;
    padding: 5px;
}

Y finalmente el archivo que recibe la respuesta de nuestra llamada AJAX.

< ?php
sleep(3);

if (empty($_POST['email'])) {
	$return['error'] = true;
	$return['msg'] = 'No ingres&oacute; mail.';
}
else {
	$return['error'] = false;
	$return['msg'] = 'Lo ingresado por ud: ' . $_POST['email'] . '.';
}

echo json_encode($return);

Hasta una próxima!!.

Advertisement

Deja un comentario

Fill in your details below or click an icon to log in:

Logo de WordPress.com

You are commenting using your WordPress.com account. Log Out / Cambiar )

Twitter picture

You are commenting using your Twitter account. Log Out / Cambiar )

Facebook photo

You are commenting using your Facebook account. Log Out / Cambiar )

Connecting to %s