Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Fernando Veloso

[Resolvido] Problema com ajax e jquery

Recommended Posts

Boa tarde!

Estou montando um site com chamadas AJAX e que deve conter uma agenda de shows, e quero implementar um calendário dinâmico para deixar a agenda mais elegante. Sendo assim, escolhi o esse modelo (http://stefanoverna.com/blog/2009/01/create-astonishing-ical-like-calendars-with-jquery.html).

 

Quando acesso minha página diretamente, o calendário funciona perfeitamente.

http://www.djallexk.com.br/agenda.php'>http://www.djallexk.com.br/agenda.php

 

Porém quando tento chamar o calendário via AJAX, o evento jquery não carrega.

http://www.djallexk.com.br e clica em 'agenda'.

 

já tentei colocar o evento '.live()', mas não obtive êxito.

 

Seguem os códigos:

 

agenda.php:

<br /><br />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>iCal-like Calendar (CSS+jQuery)</title>
	<link rel="stylesheet" href="/agenda/css/master.css" type="text/css" media="screen" charset="utf-8" />
	<script src="jquery-1.7.1.min.js" type="text/javascript"> </script>
	<script src="/agenda/js/coda.js" type="text/javascript"> </script>
</head>
   <center>
<body id="agenda">
	<h1>Agenda</h1>
	<table class="tb_agenda" cellspacing="0">
		<thead>
			<tr>
				<th>Seg</th><th>Ter</th><th>Qua</th>
				<th>Qui</th><th>Sex</th><th>Sab</th>
				<th>Dom</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td class="padding" colspan="3"></td>
				<td> 1</td>
				<td> 2</td>
				<td> 3</td>
				<td> 4</td>
			</tr>
			<tr>
				<td> 5</td>
				<td> 6</td>
				<td> 7</td>
				<td> 8</td>
				<td class="today"> 9</td>
				<td>10</td>
				<td>11</td>
			</tr>
			<tr>
				<td>12</td>
				<td class="date_has_event">
					13
					<div class="events">
						<ul>
							<li>
								<span class="title">Event 1</span>
								<span class="desc">Lorem ipsum dolor sit amet, consectetu adipisicing elit.</span>
							</li>
							<li>
								<span class="title">Event 2</span>
								<span class="desc">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
							</li>
						</ul>
					</div>
				</td>
				<td>14</td>
				<td>15</td>
				<td>16</td>
				<td>17</td>
				<td>18</td>
			</tr>
			<tr>
				<td>19</td>
				<td>20</td>
				<td>21</td>
				<td class="date_has_event">
					22
					<div class="events">
						<ul>
							<li>
								<span class="title">Event 1</span>
								<span class="desc">Lorem ipsum dolor sit amet, consectetu adipisicing elit.</span>
							</li>
							<li>
								<span class="title">Event 2</span>
								<span class="desc">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
							</li>
						</ul>
					</div>
				</td>
				<td>23</td>
				<td>24</td>
				<td>25</td>
			</tr>	
			<tr>
				<td>26</td>
				<td>27</td>
				<td>28</td>
				<td>29</td>
				<td>30</td>
				<td>31</td>
				<td class="padding"></td>
			</tr>
		</tbody>
		<tfoot>
               <th>Seg</th><th>Ter</th><th>Qua</th>
               <th>Qui</th><th>Sex</th><th>Sab</th>
               <th>Dom</th>
		</tfoot>
	</table>
</body>
   </center>
</html>

 

coda.js:

jQuery(function($) {
$('.date_has_event').each(function () {
	// options
	var distance = 10;
	var time = 250;
	var hideDelay = 500;

	var hideDelayTimer = null;

	// tracker
	var beingShown = false;
	var shown = false;

	var trigger = $(this);
	var popup = $('.events ul', this).css('opacity', 0);

	// set the mouseover and mouseout on both element
	$([trigger.get(0), popup.get(0)]).mouseover(function () {
		// stops the hide event if we move from the trigger to the popup element
		if (hideDelayTimer) clearTimeout(hideDelayTimer);

		// don't trigger the animation again if we're being shown, or already visible
		if (beingShown || shown) {
			return;
		} else {
			beingShown = true;

			// reset position of popup box
			popup.css({
				bottom: 20,
				left: -76,
				display: 'block' // brings the popup back in to view
			})

			// (we're using chaining on the popup) now animate it's opacity and position
			.animate({
				bottom: '+=' + distance + 'px',
				opacity: 1
			}, time, 'swing', function() {
				// once the animation is complete, set the tracker variables
				beingShown = false;
				shown = true;
			});
		}
	}).mouseout(function () {
		// reset the timer if we get fired again - avoids double animations
		if (hideDelayTimer) clearTimeout(hideDelayTimer);

		// store the timer so that it can be cleared in the mouseover if required
		hideDelayTimer = setTimeout(function () {
			hideDelayTimer = null;
			popup.animate({
				bottom: '-=' + distance + 'px',
				opacity: 0
			}, time, 'swing', function () {
				// once the animate is complete, set the tracker variables
				shown = false;
				// hide the popup entirely after the effect (opacity alone doesn't do the job)
				popup.css('display', 'none');
			});
		}, hideDelay);
	});
});
});

 

Desde já agradeço a atenção!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Compartilhar este post


Link para o post
Compartilhar em outros sites

 

William, obrigado pelo retorno.

Porém, no exemplo que estou utilizando não existe nenhuma chamada parecida com essa abaixo citada no seu artigo:

    $(document).ready(function() {  
       $('#content').load('lightbox.html');  
       $('#gallery a').lightBox();  
   });  

 

A página coda.js é carregada no cabeçalho e faz um varredura procurando todos os campos que possuem o class 'date_has_event' e aplica os efeitos.

 

Pode me auxiliar em como aplicar a sua solução na minha aplicação?

 

Obrigado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Porém quando tento chamar o calendário via AJAX, o evento jquery não carrega.

ok, cadê a sua chamada ajax ?

Compartilhar este post


Link para o post
Compartilhar em outros sites

William,

A chamada é feita na página index.php.

Faço uma consulta no banco para trazer as opções do menu, e monto o menu de acordo com o retorno do banco.

Quando o usuário clica em uma opção do menu, é executado o evento onclick que chama a função 'GetPagina' passando o nome da página que será exibida.

 

index.php

<?php 
include "banco";
include "ajax.js";

$sql = "select id_menu,desc_menu,ordem,display_menu from tb_menu order by ordem asc";
bd_exec($sql);

?>
<!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" />
<meta http-equiv="content-language" content="pt-br">
<meta name="author" content="Fernando Veloso da Silva">
<meta name="reply-to" content="fernando@fernandoveloso.info">
<meta name="description" content="DJ Allex K - O melhor para a sua festa!" />
<meta name="keywords" content="DJ,Allex k, DJ Allex K, dj musica, musica, som, balada, festa, dj para festas, flash back, dj balada" />
<meta name="robots" content="index,follow">
<title>| DJ Allex K |</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" href="nivo-slider.css" type="text/css" media="screen" />
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.nivo.slider.pack.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript" src="swfobject.js" ></script>
</head>
<body>
<form id="frm_page" name="frm_page" method="post" action="">
<input type="hidden" id="page_name" name="page_name" value="" />
</form>
<div class="content">
       <div class="header">
           <!--<img align="right" src="img/bg_page2.jpg" alt="img/bg_page2.jpg" border="0" />-->
           <div class="social">
               <a href="http://www.facebook.com/people/Allex-K-Karelli/100000332164597" target="_blank"><img src="img/facebook.png" alt="img/facebook.png" title="Facebook" border="0" /></a>
                 
               <a href="https://twitter.com/#!/@djallexkoficial" target="_blank"><img src="img/twitter.png" alt="img/twitter.png" title="Twitter" border="0" /></a>
                 
               <a href="http://www.myspace.com/djallexk" target="_blank"><img src="img/myspace.png" alt="img/myspace.png" title="MySpace" border="0" /></a>
           </div>
       </div>
       <div class="menu">
       	<table class="tb_menu" cellpadding="3" cellspacing="1">
           	<tr>
			<?php
               	while(bd_proxima()){
					echo "<td id=\"".bd_coluna('desc_menu').".php\"><a href=\"javascript:void(0);\" onmouseover=\"Menu_select('".bd_coluna('desc_menu')."');\" onmouseout=\"Menu_deselect('".bd_coluna('desc_menu')."');\" onclick=\"GetPagina('".bd_coluna('desc_menu').".php'); return false;\"><font id=\"font_".bd_coluna('desc_menu')."\" color=\"".$menubg_color."\">".bd_coluna('display_menu')."</font></a></td>";
				}
               ?>
               </tr>
           </table>
       </div>
       <div style="width:100%; height:305px;">
           <div style="float:left; width:190px; height:300px; margin-top:10px;">
               <img src="img/fire2.gif" alt="img/fire2.gif" />
           </div>
           <div id="slider" class="nivoSlider" style="float:left;">
               <img src="images/publico2.jpg" alt="images/publico2.jpg" />
               <img src="images/DSC_93712.jpg" alt="images/DSC_93712.jpg" />
               <img src="images/Figura22.jpg" alt="images/Figura22.jpg" />
           </div>
           <div style="float:left; width:190px; height:300px; margin-top:10px; margin-left:10px;">
               <img src="img/fire.gif" alt="img/fire.gif" />
           </div>
	</div>
	<div class="page" id="page">
       </div>
       <div class="footer">
       	<div style="float:left;">2012 - © Allex K, all rights reserved.</div>
           <!-- Div that contains player. -->
           <div id="player" style="float:left; margin-left:150px;">
           <h1>No flash player!</h1>
           <p>It looks like you don't have flash player installed. <a href="http://www.macromedia.com/go/getflashplayer" >Click here</a> to go to Macromedia download page.</p>
           </div>
           <div align="right">Powered By <a href="http://www.fernandoveloso.info" target="_blank" title="Fernando Veloso" style="text-decoration:none; color:#6C6;">Fernando Veloso</a></div>
       </div>
       <div id="teste">
       </div>
</div>
</body>
</html>
<script language="javascript" type="text/javascript">

$(function(){
	$(window).load(function() {
		$('#slider').nivoSlider({
			effect: 'random',
			pauseOnHover: true
		});
	}); 
});

function GetPagina(pagina){
	loadXMLDoc(pagina,'page');
}

function Menu_select(item_menu){
	document.getElementById('font_'+item_menu).style.color="#B70000";
}

function Menu_deselect(item_menu){
	document.getElementById('font_'+item_menu).style.color="#000000";
}

   function validaFormContato(site) {
       var nome = document.getElementById('nome').value;
       var email = document.getElementById('email').value;
       var assunto = document.getElementById('assunto').value;
       var mensagem = document.getElementById('mensagem').value;

       if (nome == ""){
           alert('Peço que informe seu nome para melhor atendê-lo!');
           document.getElementById('nome').focus();
           return false;
       } 

       if (email == ""){
           alert('Peço que informe seu email para melhor atendê-lo!');
           document.getElementById('email').focus();
           return false;
       } 

       if (assunto == ""){
           alert('Peço que informe o assunto desse contato!');
           document.getElementById('assunto').focus();
           return false;
       } 

       if (mensagem == ""){
           alert('Peço que descreva o motivo desse contato!');
           document.getElementById('mensagem').focus();
           return false;
       } 

       if (confirm('Deseja realmente enviar essa mensagem?')){
               document.getElementById('enviar').disabled = "true";
			document.getElementById('site').value = site;
			document.getElementById('act').value = "gravar_contato";
			document.getElementById('frm_contato').submit();
               return true;
       }
}  
<!-- Script that embeds player. -->

var so = new SWFObject("flashmp3player.swf", "player", "290", "100", "9"); // Location of swf file. You can change player width and height here (using pixels or percents).
so.addParam("quality", "high");
so.addVariable("content_path","mp3"); // Location of a folder with mp3 files (relative to php script).
so.addVariable("color_path","default.xml"); // Location of xml file with color settings.
so.addVariable("script_path","flashmp3player.php"); // Location of php script.
so.write("player");

GetPagina('<?php echo $page_name; ?>');
</script>

 

ajax.js

<script>	
var lugar;
function loadXMLDoc(url, local)
{ 	
var oHTTPRequest = createXMLHTTP(); 
oHTTPRequest.open("get", url, true);
oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oHTTPRequest.onreadystatechange=function(){
	document.getElementById(local).innerHTML= "<img src='../imagens/ajax_loader.gif'> Carregando...";
	if (oHTTPRequest.readyState==4){				
	var resultado = oHTTPRequest.responseText;
	document.getElementById(local).innerHTML = resultado;
	}
}
oHTTPRequest.send(null);
}

//cria objeto ajax
function createXMLHTTP() {
	var ajax;
	try {
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(e) {
			try {
				ajax = new ActiveXObject("Msxml2.XMLHTTP");
			alert(ajax);
		} catch(ex) {
			try {
				ajax = new XMLHttpRequest();
			} catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				ajax = null;
			}
		}
		return ajax;
		}

		var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
		for (var i=0; i < arrSignatures.length; i++) {
			try {
				var oRequest = new ActiveXObject(arrSignatures[i]);
				return oRequest;
			} catch (oError) {
		}
	}
	throw new Error("MSXML Não está instalado");
}
</script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Quando o usuário clica em uma opção do menu, é executado o evento onclick que chama a função 'GetPagina' passando o nome da página que será exibida.

então é neste instante em que você deve chamar o teu "plugin".

 

pseudocodigo:

 

 

//ajax

// colocando o retorno do ajax na pagina

//chame o teu plugin de calendario aqui, logo depois de colocar o html na pagina q veio do ajax.

Compartilhar este post


Link para o post
Compartilhar em outros sites

William,

 

Assim?

	function GetPagina(pagina){
	loadXMLDoc(pagina,'page');

	$(document).ready(function() {  
		$('#page').load('agenda.php',  
			function(){  
				$('.date_has_event').Agenda();  
			}  
		);  
	});  
}

Dá erro de javascript informando que na linha onde consta '$('.date_has_event').Agenda(); ' o objeto não suporta a propriedade ou método.

Compartilhar este post


Link para o post
Compartilhar em outros sites

quase isso..

 

 

lembre-se q para usar o $, você precisa importar o jQuery em cima(por isso apareceu esse erro pra ti).

é aqui que você coloca o html no documento:

 

function loadXMLDoc(url, local)
{       
       var oHTTPRequest = createXMLHTTP(); 
       oHTTPRequest.open("get", url, true);
       oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       oHTTPRequest.onreadystatechange=function(){
               document.getElementById(local).innerHTML= "<img src='../imagens/ajax_loader.gif'> Carregando...";
               if (oHTTPRequest.readyState==4){                                
               var resultado = oHTTPRequest.responseText;
               document.getElementById(local).innerHTML = resultado;

                   //é aqui que você deve chamar o teu plugin
               }
       }
       oHTTPRequest.send(null);
}

 

desculpe a pergunta, mas pq você não faz ajax com jQuery também ?

Compartilhar este post


Link para o post
Compartilhar em outros sites

William,

Alterando para o ajax com jquery, fica assim?

	function GetPagina(pagina){
	$(function(){

		$('#'+pagina+'').click(function(){

			$.ajax({

				type: 'get',

				//data: 'nome=Usuario&email=usuario@servidor.com',

				url:pagina,

				success: function(retorno){

					$('#'+pagina+'').html(retorno);  
				}
			})
		})
	})
}

 

Desta forma que fiz nenhuma página está sendo exibida...

E utilizando o ajax com jquery, basta colocar a chamada calendário dentro do 'sucess:'?

Compartilhar este post


Link para o post
Compartilhar em outros sites

hum.. quase amigo...

 

olha, esquece a tua implementação de ajax, e faz de novo, com base nestes dois links, ok?

 

 

http://wbruno.com.br/2011/03/30/navegacao-sem-refresh-carregando-conteudo-ajax-em-div/

http://wbruno.com.br/2011/08/22/usando-lightbox-em-pagina-carregada-ajax/

Compartilhar este post


Link para o post
Compartilhar em outros sites

William,

Estou quase lá... rs

 

Já fiz a implementação de ajax de acordo com o seu artigo, e está funcionando perfeitamente, mas ainda estou apanhando do calendário.

 

Defini a chamada do plugin da seguinte forma:

<script type="text/javascript">  
$(document).ready(function(){  
	$("#tb_menu a").click(function( e ){  
		e.preventDefault();  
		var href = $( this ).attr('href');  
		$("#page").load(href);

		if(href == "agenda.php"){
			$('#page').load('agenda.php',  
				function(){  
					$('.date_has_event').Agenda();  
				}  
			);  
		}
	});  
});  
</script> 

 

Mas não está funcionando...

 

William,

Consegui!

 

Apenas deixei de chamar o jquery na pagina agenda.php, deixando apenas a chamada do plugin.

Assim nem precisei realizar a chamada de alguma função específica.

 

Muito obrigado pelo auxílio!

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.