<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Cuadernodeapuntes.es &#187; AJAX</title>
	<atom:link href="http://www.cuadernodeapuntes.es/category/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cuadernodeapuntes.es</link>
	<description>Apuntes de informática</description>
	<lastBuildDate>Wed, 23 Jun 2010 17:58:36 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Ajax con JQuery</title>
		<link>http://www.cuadernodeapuntes.es/2010/01/ajax-con-jquery/</link>
		<comments>http://www.cuadernodeapuntes.es/2010/01/ajax-con-jquery/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 17:46:07 +0000</pubDate>
		<dc:creator>Jrt_1990</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Memorias]]></category>
		<category><![CDATA[Sinpastaenelbolsillo.com]]></category>
		<category><![CDATA[TEWC]]></category>
		<category><![CDATA[Tutoriales]]></category>

		<guid isPermaLink="false">http://www.cuadernodeapuntes.es/?p=214</guid>
		<description><![CDATA[
			
				
			
		
Después de la "resaca" de la nochevieja, y de felicitar el 2010 (o 1948), es hora de ponerse las pilas y empezar con algo serio.
Esta vez voy a contar como utilizar JQuery para implementar AJAX en tu página web, y de qué manera puedes solventar el mayor problema que tiene AJAX ahora mismo, que no ]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.cuadernodeapuntes.es%2F2010%2F01%2Fajax-con-jquery%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.cuadernodeapuntes.es%2F2010%2F01%2Fajax-con-jquery%2F&amp;source=capuntes&amp;style=normal&amp;service=TinyURL.com" height="61" width="50" /><br />
			</a>
		</div>
<p>Después de la "resaca" de la nochevieja, y de <a href="http://www.cuadernodeapuntes.es/2009/12/feliz-ano-a-todos-los-lectores/">felicitar el 2010</a> (o <a href="http://generacionnegativa.blogspot.com/2007/01/feliz-1984.html">1948</a>), es hora de ponerse las pilas y empezar con algo serio.<br />
Esta vez voy a contar como utilizar JQuery para implementar AJAX en tu página web, y de qué manera puedes solventar el mayor problema que tiene AJAX ahora mismo, que no es otro que la indexacion por parte de los buscadores como Google.</p>
<p>Antes de empezar voy a realizar una breve introducción a AJAX,y a comentar las ventajas y desventajas que trae, y para empezar, tengo que decir que AJAX, siglas de <em><strong>A</strong>synchronous <strong>J</strong>avaScript <strong>A</strong>nd <strong>X</strong>ML</em>, es un conjunto de 4 tecnologías que sirve para comunicar el navegador con el servidor sin necesidad de recargar la página.<br />
Esto nos brinda muchas oportunidades, ya que, junto con los efectos de JQuery se pueden lograr cosas sorprendentes, y además, como no hace falta recargar la página, podemos ahorrar ancho de banda, lo que reduce la carga del servidor.</p>
<p>No voy a entrar más en detalle, para más información puedes acceder a la <a href="http://es.wikipedia.org/wiki/AJAX">Wikipedia</a>, o buscar en Google, pero ahora vamos a implementarlo.</p>
<h2><span id="more-214"></span>Funciones AJAX de JQuery</h2>
<p>JQuery ya viene con <a href="http://docs.jquery.com/Ajax">AJAX </a>de serie, y tiene multitud de funciones muy simples que se encargan de realizar toda la labor "chunga", pero de momento con la función <a href="http://docs.jquery.com/Ajax/load">load()</a>, de momento , nos vale.</p>
<p>El funcionamiento es muy sencillo, aunque se puede complicar más para realizar peticiones mas complejas, no es necesario, y para ellas recurriremos a la función <a href="http://docs.jquery.com/Ajax/jQuery.ajax">ajax()</a>.</p>
<h3>Load()</h3>
<p>Espero que no te importe estimado navegante, que para explicar la función utilice el código de mi <a href="http://www.sinpastaenelbolsillo.com/empresas/1.html">web para ganar dinero</a>, ya que es un código que de momento funciona, y puedes ver en cualquier momento.</p>
<p>La solución al problema de los buscadores es "sencilla" pero laboriosa, ya que se trata de realizar la página sin AJAX y de manera que funcione, y después introducir el atributo <em>rel</em> en donde pondremos la url que queramos llamar para cargar, de manera que los navegadores que no tienen Javascript (como los rastreadores de Google) puedan navegar por la página, y así también, si alguien abre algún enlace en una pestaña nueva, se cargará correctamente.</p>
<p>Para la función <em>load()</em> voy a usar de ejemplo el calendario que hay en Sinpasta, ya que funciona tanto por AJAX como sin el, y su funcionamiento es muy sencillo.<br />
Antes de poner el código HTML, tengo que decir que hay un fichero, llamado <em>ajax.php</em> que simplemente recibe por parámetro una url de un archivo, y lo incluye, lo uso para evitar tener líos con las rutas relativas, y que es el que se encarga de llamar a <em>calendar.php</em>, que es el que genera toda la vista HTML del calendario.</p>
<p>El código HTML de los enlaces que hacen que el calendario cambie la vista del mes es el siguiente:</p>
<div class="igBar"><span id="lhtml-4"><a href="#" onclick="javascript:showPlainTxt('html-4'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">HTML:</span>
<div id="html-4">
<div class="html">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #ddbb00;">&amp;lt;</span>a title=&quot;Diciembre&quot; href=&quot;/index.php?fecha=2009-12&quot; rel=&quot;ajax.php?var=includes/sidebar/calendar.php<span style="color: #ddbb00;">&amp;amp;</span>amp;fecha=2009-12&quot;<span style="color: #ddbb00;">&amp;gt;</span>« Diciembre<span style="color: #ddbb00;">&amp;lt;</span>/a<span style="color: #ddbb00;">&amp;gt;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Como puedes observar, el atributo <em>href</em> hace referencia a un archivo distinto que el atributo <em>rel</em>, a continuación pongo el Javascript necesario para que funcione con AJAX</p>
<div class="igBar"><span id="ljavascript-5"><a href="#" onclick="javascript:showPlainTxt('javascript-5'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">JavaScript:</span>
<div id="javascript-5">
<div class="javascript">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"#prev a"</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">livequery</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'click'</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"#calendario .sidebarcontent"</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">rel</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Acabo de caer en que no he explicado livequery, y es un plugin realmente importante, así que voy a explicarlo ahora, de momento, del código anterior sólamente fijate en las líneas que hay dentro de <em>function</em>.<br />
En la primera puedes ver el funcionamiento de <em>load</em>, que lo único que hace es pedir al servidor el fichero que se encuentra donde especifica el atributo rel del elemento que lo ha llamado, y lo mete dentro de <strong>"#calendario .sidebarcontent"</strong>.<br />
En la segunda se devuelve <strong>false</strong>, de este modo el navegador no se dirigirá hacia donde apunta el atributo <em>href</em>.</p>
<h3>Pequeña pausa para explicar LiveQuery</h3>
<p>Si estás realizando una página web con AJAX, puede que te aya surgido el problema de que cargas una parte de la página con AJAX, y que de repente todos las acciones que tendrían que realizarse a través de JavaScript dentro de la parte que has cargado por AJAX no funcionan, eso es debido a que el JavaScript se aplica sobre la página una vez cargada, y al cargar nuevos elementos, no se les aplica el tratamiento JavaScript y por lo tanto no funciona.<br />
Para solucionarlo tenemos el plugin <a href="http://plugins.jquery.com/project/livequery/">LiveQuery</a>. Se instala igual que todos, y su funcionamiento es muy simple, tan sólo tienes que llamar a la función <em>livequery</em> que toma dos atributos, el primero el el "disparador", en el ejemplo anterior, era <em>click</em>, que es como si se hubiera puesto <strong>.click(function(){</strong>, pero eso no hubiera funcionado bien. El segundo atributo es la función que se va a realizar.</p>
<h3>ajax()</h3>
<p>Una vez vista la función <em>load</em>, vamos a ver como enviar un formulario a través de AJAX, ahora con la función <em>ajax()</em>, valga la redundancia.<br />
El código HTML es el que uso en <a href="http://www.sinpastaenelbolsillo.com/empresas/1.html">Sinpasta</a>, no lo voy a poner porque es muy largo y es un formulario normal, sólo que cada input tiene una <em>id</em> para acceder a él a través de los selectores de JQuery.</p>
<p>El código Javascript es el siguiente:</p>
<div class="igBar"><span id="ljavascript-6"><a href="#" onclick="javascript:showPlainTxt('javascript-6'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">JavaScript:</span>
<div id="javascript-6">
<div class="javascript">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"#comentario_button"</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">livequery</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'click'</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #003366; font-weight: bold;">var</span> noticia = $<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"#noticia"</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">attr</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"value"</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #003366; font-weight: bold;">var</span> autor = $<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"#autor"</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">attr</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"value"</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #003366; font-weight: bold;">var</span> correo = $<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"#correo"</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">attr</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"value"</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #003366; font-weight: bold;">var</span> url = $<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"#url"</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">attr</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"value"</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #003366; font-weight: bold;">var</span> comentario = $<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"#comentario"</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">attr</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"value"</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #003366; font-weight: bold;">var</span> dataString = <span style="color: #3366CC;">'autor='</span>+ autor + <span style="color: #3366CC;">'&amp;amp;correo='</span> + correo + <span style="color: #3366CC;">'&amp;amp;url='</span> + url + <span style="color: #3366CC;">'&amp;amp;comentario='</span> + comentario + <span style="color: #3366CC;">'&amp;amp;noticia='</span> + noticia;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'#comentarios'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">empty</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'#comentarios'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">hide</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'#formulario'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">empty</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'#formulario'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">hide</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$.<span style="color: #006600;">ajax</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">type: <span style="color: #3366CC;">"POST"</span>,</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">url: <span style="color: #3366CC;">"/ajax.php?var=includes/content/formulario.php&amp;amp;noticia="</span> + noticia,</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">data: dataString,</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">dataType: <span style="color: #3366CC;">"html"</span>,</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">success: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>respuesta<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'#formulario'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">html</span><span style="color: #66cc66;">&#40;</span>respuesta<span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'#comentarios'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"/ajax.php?var=includes/content/comentarios.php&amp;amp;noticia="</span> + noticia, <span style="color: #003366; font-weight: bold;">null</span>, <span style="color: #003366; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'#formulario'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">fadeIn</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"1500"</span>, <span style="color: #003366; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'#comentarios'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">fadeIn</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">"1500"</span>, <span style="color: #003366; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Como puedes observar, he usado livequery, ya que el formulario va dentro de una parte de la página que se carga con AJAX, lo siguiente es meter en variables los campos que rellena el navegante.<br />
Después genero una String que será la que se pase en forma de petición POST al servidor, con la funcion <em>ajax()</em>, pero antes elimino todo el html que tiene el <strong>#formulario</strong> y <strong>#comentarios</strong> y los oculto.<br />
Lo que voy a comentar ahora linea a linea es lo que hay dentro de la funcion <em>ajax()</em>, que es lo más interesante:</p>
<ol>
<li>Lo primero que hago es definir el tipo de petición que es, en este caso, al enviar el formulario, prefiero que sea POST.</li>
<li>La url a donde ha de ir la petición, como siempre, a través de ajax.php.</li>
<li><strong>data</strong> hace referencia a los datos que hay que pasar, en este caso la url pasada antes.</li>
<li>El <strong>datatype</strong> indica que los datos van en HTML.</li>
<li>En esta línea indico la función que quiero que se realize, pasando como parámetro la respuesta a la petición POST.</li>
<li>Cargo el HTML de la respuesta en <strong>#formulario</strong> y en <strong>#comentarios</strong> cargo todos los comentarios de esa entrada.</li>
<li>Para acabar hago que tanto <strong>#formulario</strong> como<strong> #comentarios</strong> aparezcan con un efecto <em>fadeIn()</em>.</li>
</ol>
<p>He quitado las comprobaciones del formulario, que el correo sea válido, que todos los campos esten completados etc... para que no sea muy largo el código.</p>
<p>Existen otras muchas funciones para utilizar AJAX con JQuery, entre ellas una de las que más uso yo es getJSON, pero es un poco más avanzada, y al menos para lo básico de AJAX con lo puesto aquí es suficiente. Si te interesa el tema del JSON espero poder publicar en breves una entrada hablando sólo de él, te invito a pasarte de vez en cuando, o a suscribirte al <a href="http://feeds.feedburner.com/Cuadernodeapuntes">feed</a> para estar al tanto de su publicación.</p>
<p>Espero que te haya gustado, y sobretodo que te haya sido útil y te haya dado ideas para mejorar tu web. Siento no haber puesto fotos, se que hacen la entrada mas amena, pero en este caso no creo que fuera necesario.</p>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 1699px; width: 1px; height: 1px;">$("#comentario_button").livequery('click', function() {<br />
var noticia = $("#noticia").attr("value");<br />
var autor = $("#autor").attr("value");<br />
var correo = $("#correo").attr("value");<br />
var url = $("#url").attr("value");<br />
var comentario = $("#comentario").attr("value");</p>
<p>if (autor == "") {<br />
$("#autor_error").show();<br />
$("#autor").focus();<br />
return false;<br />
}</p>
<p>if (correo == "") {<br />
$("#correo_error").show();<br />
$("#correo").focus();<br />
return false;<br />
}</p>
<p>if (comentario == "") {<br />
$("#comentario_error").show();<br />
$("#comentario").focus();<br />
return false;<br />
}</p>
<p>var dataString = 'autor='+ autor + '&amp;correo=' + correo + '&amp;url=' + url + '&amp;comentario=' + comentario + '&amp;noticia=' + noticia;</p>
<p>$('#comentarios').empty();<br />
$('#comentarios').hide();<br />
$('#formulario').empty();<br />
$('#formulario').hide();</p>
<p>$.ajax({<br />
type: "POST",<br />
url: "/ajax.php?var=includes/content/formulario.php&amp;noticia=" + noticia,<br />
data: dataString,<br />
dataType: "html",<br />
success: function(respuesta) {<br />
$('#formulario').html(respuesta);<br />
$('#comentarios').load("/ajax.php?var=includes/content/comentarios.php&amp;noticia=" + noticia, null, null);<br />
$('#formulario').fadeIn("1500", null);<br />
$('#comentarios').fadeIn("1500", null);<br />
}<br />
});</p>
<p>return false;<br />
});</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.cuadernodeapuntes.es/2010/01/ajax-con-jquery/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
