Foros del Web » Programando para Internet » Javascript »

2 ajax no funcionan

Estas en el tema de 2 ajax no funcionan en el foro de Javascript en Foros del Web. hola chicos, tengo un problema... sería genial si pudieran ayudarme a resolverlo =). tengo una pagina y debo recolectar información de otras 2 con un ...
  #1 (permalink)  
Antiguo 04/06/2013, 16:17
 
Fecha de Ingreso: abril-2013
Mensajes: 4
Antigüedad: 11 años
Puntos: 0
2 ajax no funcionan

hola chicos, tengo un problema... sería genial si pudieran ayudarme a resolverlo =).

tengo una pagina y debo recolectar información de otras 2 con un ajax pero solamente funciona uno de ellos y no se porque (la verdad soy nuevo en javascript). este es mi código:

Código:
 <script>
function encontrarnumero(){ //este es el ajax
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
var divid='u219-4';


if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
document.getElementById(divid).innerHTML=xmlhttp.responseText;
setInterval(encontrarnumero,1000);

 
}
};
xmlhttp.open("GET","numero.php?q="+q+"&p="+p+"&w="+w,true);
xmlhttp.send();
}

window.onload=function(){
    encontrarnumero();
};
</script> 
<script>
function encontrartiempo(){ //este es el ajax
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
var divid='tiempo';


if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
document.getElementById(divid).innerHTML=xmlhttp.responseText;
setInterval(encontrartiempo,2000);

 
}
};
xmlhttp.open("GET","tiempo.php?q="+q+"&p="+p+"&w="+w,true);
xmlhttp.send();
}

window.onload=function(){
    encontrartiempo();
};
 
</script>
de las paginas en php no se preocupen ya que están bien.

gracias de antemano
  #2 (permalink)  
Antiguo 04/06/2013, 16:49
 
Fecha de Ingreso: abril-2011
Mensajes: 1.342
Antigüedad: 13 años
Puntos: 344
Respuesta: 2 ajax no funcionan

No puedes asignar el evento onload dos veces, porque sólo queda la última vez que lo asignas.

Código Javascript:
Ver original
  1. <script>
  2.     function encontrarnumero(){ //este es el ajax
  3.        
  4.         var divid='u219-4';
  5.  
  6.         if (window.XMLHttpRequest)
  7.         {// code for IE7+, Firefox, Chrome, Opera, Safari
  8.             xmlhttp=new XMLHttpRequest();
  9.         }
  10.         else
  11.         {// code for IE6, IE5
  12.             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  13.         }
  14.         xmlhttp.onreadystatechange=function()
  15.         {
  16.             if (xmlhttp.readyState===4 && xmlhttp.status===200)
  17.             {
  18.                 document.getElementById(divid).innerHTML=xmlhttp.responseText;
  19.                 setInterval(encontrarnumero,1000);
  20.  
  21.  
  22.             }
  23.         };
  24.         xmlhttp.open("GET","numero.php?q="+q+"&p="+p+"&w="+w,true);
  25.         xmlhttp.send();
  26.     }
  27.  
  28.     function encontrartiempo(){ //este es el ajax
  29.        
  30.         var divid='tiempo';
  31.  
  32.  
  33.         if (window.XMLHttpRequest)
  34.         {// code for IE7+, Firefox, Chrome, Opera, Safari
  35.             xmlhttp=new XMLHttpRequest();
  36.         }
  37.         else
  38.         {// code for IE6, IE5
  39.             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  40.         }
  41.         xmlhttp.onreadystatechange=function()
  42.         {
  43.             if (xmlhttp.readyState===4 && xmlhttp.status===200)
  44.             {
  45.                 document.getElementById(divid).innerHTML=xmlhttp.responseText;
  46.                 setInterval(encontrartiempo,2000);
  47.  
  48.  
  49.             }
  50.         };
  51.         xmlhttp.open("GET","tiempo.php?q="+q+"&p="+p+"&w="+w,true);
  52.         xmlhttp.send();
  53.     }
  54.  
  55.  
  56.     window.onload=function(){
  57.         encontrarnumero();
  58.         encontrartiempo();
  59.     };
  60. </script>

Te recomiendo aun así que uses jquery u otra librería que facilita muchos las llamadas ajax o si no quieres, create una función para reutilizar el código repetido.

Un saludo.
  #3 (permalink)  
Antiguo 04/06/2013, 19:35
 
Fecha de Ingreso: abril-2013
Mensajes: 4
Antigüedad: 11 años
Puntos: 0
Respuesta: 2 ajax no funcionan

Muchas gracias a los que respondieron, efectivamente el problema era que no podía hacer 2 veces window.onload... finalmente la solución fue hacer una función. la dejo a continuación por si alguien tiene el mismo problema:

Código:
<script>
// Move repeating code to a function
function doAJAX(divid, page) {
    if (window.XMLHttpRequest) {
        // Use `var` when declaring variables
        var xmlhttp = new XMLHttpRequest();
    } else {
        var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            document.getElementById(divid).innerHTML = xmlhttp.responseText;

            // Use `setTimeout` if you're going to make recursive calls!
            setTimeout(function() {
                doAJAX(divid, page)
            }, 1000);
        }
    };
    xmlhttp.open("GET", page + "?q=" + q + "&p=" + p + "&w=" + w, true);
    xmlhttp.send();
}

// Just one onload handler that calls the function twice,
//    passing the different info for each call
window.onload = function () {
    doAJAX('u219-4', "numero.php");
    doAJAX('tiempo', "tiempo.php");
};
</script>
  #4 (permalink)  
Antiguo 04/06/2013, 19:57
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: 2 ajax no funcionan

No hay ningún impedimento para hacer varias llamadas simultaneas a Ajax, ni siquiera sería necesario utilizar el evento onload.

Este ejemplo es algo rebuscado, pero hace 3 llamadas a diferentes intervalos al mismo archivo, aunque podrían ser diferentes
Código 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>
<title>titulo</title> 
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
div{
width: 300px;
height: 20px;
padding: 5px;
margin: 2px;
border: dotted 1px #666;
}
</style>
<script type="text/javascript">
//<![CDATA[
// agrega un parametro unico al archivo
var prevenirCache=1;
// innerHtml para imagen o texto Ajax en espera
var loaderGif = "<p style='font-size:10pt;display:inline-block; text-align: center; margin-top: 25%;'><img src='ajax-loader.gif' alt='Cargando datos' \/><br \/> Aguarde por favor...<\/p>";

/*** no editar ***/
var cargarObjetos="";
var rootdomain="http://"+window.location.hostname;
var cacheParam="";
function cargarAjax(url,divAjax){
var contenidoAjax = false;

if(window.XMLHttpRequest) {
contenidoAjax = new XMLHttpRequest();
}else if(window.ActiveXObject) {
contenidoAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
alert('Su navegador no soporta Ajax');
}

contenidoAjax.onreadystatechange=function(){
cargaPagina(contenidoAjax,divAjax);
}
                
if(prevenirCache == 1){
    cacheParam=(url.indexOf("?")!=-1)? "&"+ new Date().getTime() : "?"+ new Date().getTime();
    }    
        contenidoAjax.open('GET', url+cacheParam, true);
    contenidoAjax.send(null);
    }
    
    
    function cargaPagina(contenidoAjax,divAjax){
        if(contenidoAjax.readyState==1){
        //    document.getElementById(divAjax).innerHTML = loaderGif;
            }
            if(contenidoAjax.readyState == 4 && (contenidoAjax.status==200 || window.location.href.indexOf("http")==-1)){
                document.getElementById(divAjax).innerHTML=contenidoAjax.responseText;
                }
                }
                

//]]>
</script>
</head>
<body>
<div>
Actualiza cada 1'' &nbsp;
<span id="uno">
<?php include('hora.php'); ?>
    <script type="text/javascript">
        setInterval("cargarAjax('hora.php','uno')", 1000);
        </script>
</span>
</div>
<div>
Actualiza cada 5'' &nbsp;
<span id="dos">
<?php include('hora.php'); ?>
        <script type="text/javascript">
        setInterval("cargarAjax('hora.php','dos')", 5000);
        </script>
</span>
</div>
<div>
Actualiza cada 10'' 
<span id="tres">
<?php include('hora.php'); ?>
        <script type="text/javascript">
        setInterval("cargarAjax('hora.php','tres')", 10000);
        </script>
</span>
</div>
</body>
</html>
hora.php

Código PHP:
<?php
echo date('H:i:s');
?>
Demo:
http://foros.emprear.com/ajax/basico...iple/index.php

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.

Etiquetas: ajax, funcion, funcionan, html, jquery, js, php
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 13:40.