Foros del Web » Programando para Internet » Javascript » Frameworks JS »

[SOLUCIONADO] Problema con estado 1 en loader

Estas en el tema de Problema con estado 1 en loader en el foro de Frameworks JS en Foros del Web. Hola, por favor tengo este código y lo que quiero es que salga la imagen de loader mientras que carga. Lo estoy intentando así pero ...
  #1 (permalink)  
Antiguo 19/01/2014, 17:40
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Problema con estado 1 en loader

Hola, por favor tengo este código y lo que quiero es que salga la imagen de loader mientras que carga. Lo estoy intentando así pero no me sale:

Código Javascript:
Ver original
  1. <script>
  2. function valida_envia(){
  3.  
  4.     var telefonos = document.forms['datos'].elements['telefonos'];
  5.     if (telefonos.value.length == 0)
  6.     {
  7.        
  8.         alert("Insertar el nº de teléfono");
  9.  
  10.         telefonos.focus();
  11.  
  12.         return 0;
  13.  
  14.     }
  15.     else
  16.     {
  17.        
  18.         if (window.XMLHttpRequest)
  19.         {
  20.             xmlhttp=new XMLHttpRequest();
  21.         }
  22.         else
  23.         {
  24.             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  25.         }  
  26.         xmlhttp.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  27.         xmlhttp.send();
  28.        
  29.        
  30.    
  31.     if (xmlhttp.readyState==1)
  32.     {
  33.        
  34.        
  35.         document.getElementById("carga1").innerHTML="<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  36.        
  37.     }
  38.    
  39.        
  40.          if (xmlhttp.readyState==4 && xmlhttp.status==200)
  41.          
  42.          
  43.              
  44.         {
  45.    
  46.            
  47.             var xml = xmlhttp.responseXML;
  48.             dato=xml.getElementsByTagName("datos");
  49.             if(dato[0].firstChild.nodeValue=="1")
  50.             {
  51.                 num_user=xml.getElementsByTagName("numusuario");
  52.                
  53.                
  54.                 document.getElementById("movil").value =xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  55.                 document.getElementById("calle").value =xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  56.                 document.getElementById("dni").value =xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  57.                 document.getElementById("name").value =xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  58.                 document.getElementById("edificio").value =xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  59.                 document.getElementById("numero").value =xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  60.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  61.                 document.getElementById("piso").value =xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  62.                 document.getElementById("letra").value =xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  63.                 document.getElementById("localidad").value =xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  64.                 document.getElementById("provincia").value =xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  65.                 document.getElementById("email").value =xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  66.                
  67.            
  68.                
  69.                  
  70.        
  71.             }
  72.             if(dato[0].firstChild.nodeValue=="0")
  73.             {                  
  74.                      envia();
  75.                          }
  76.                          else{
  77.                              
  78.             }
  79.         }
  80.  
  81.     }
  82.  }



Esta línea creo que no esta bien:

Código Javascript:
Ver original
  1. if (xmlhttp.readyState==1)
  2.     {
  3.        
  4.        
  5.         document.getElementById("carga1").innerHTML="<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  6.        
  7.     }


Gracias
  #2 (permalink)  
Antiguo 19/01/2014, 18:16
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Problema con estado 1 en loader

Tuve un problema similar elaborando mi función Ajax, pero lo resolví retrasando la ejecución de la respuesta del servidor. Lo que sucede es que la respuesta es tan rápida, que no alcanza el tiempo para que aparezca el gif de carga, pero si retrasas las instrucciones que se ejecutan cuando recibes la respuesta, podrás ver el gif.

Código Javascript:
Ver original
  1. if (xmlhttp.readyState < 4) {
  2.     document.getElementById("carga1").innerHTML = "<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  3. }
  4. else {
  5.     if (xmlhttp.readyState==4 && xmlhttp.status==200) {
  6.         setTimeout(function() {
  7.             var xml = xmlhttp.responseXML;
  8.             dato = xml.getElementsByTagName("datos");
  9.             if (dato[0].firstChild.nodeValue == "1") {
  10.                 num_user = xml.getElementsByTagName("numusuario");
  11.  
  12.                 document.getElementById("movil").value = xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  13.                 document.getElementById("calle").value = xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  14.                 document.getElementById("dni").value = xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  15.                 document.getElementById("name").value = xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  16.                 document.getElementById("edificio").value = xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  17.                 document.getElementById("numero").value = xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  18.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  19.                 document.getElementById("piso").value = xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  20.                 document.getElementById("letra").value = xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  21.                 document.getElementById("localidad").value = xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  22.                 document.getElementById("provincia").value = xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  23.                 document.getElementById("email").value = xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  24.             }
  25.            
  26.             if(dato[0].firstChild.nodeValue=="0")
  27.                 envia();
  28.         }, 1500);
  29.     }
  30. }

Con el método setTimeout, retraso 1500 milisegundos o 1.5 segundos, la ejecución de las instrucciones que ocurrirán cuando se reciba la respuesta del servidor.

Saludos
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #3 (permalink)  
Antiguo 20/01/2014, 02:07
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Gracias Alexis, pero no sale. Me dice que tarda 200 OK 877ms, y eso que le he dado mas tiempo.

Código Javascript:
Ver original
  1. function valida_envia(){
  2.  
  3.     var telefonos = document.forms['datos'].elements['telefonos'];
  4.     if (telefonos.value.length == 0)
  5.     {
  6.        
  7.         alert("Insertar el nº de teléfono");
  8.  
  9.         telefonos.focus();
  10.  
  11.         return 0;
  12.  
  13.     }
  14.     else
  15.     {
  16.        
  17.         if (window.XMLHttpRequest)
  18.         {
  19.             xmlhttp=new XMLHttpRequest();
  20.         }
  21.         else
  22.         {
  23.             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  24.         }  
  25.         xmlhttp.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  26.         xmlhttp.send();
  27.        
  28.        
  29.     if (xmlhttp.readyState < 4) {
  30.     document.getElementById("carga1").innerHTML = "<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  31. }
  32. else {
  33.     if (xmlhttp.readyState==4 && xmlhttp.status==200) {
  34.         setTimeout(function() {
  35.             var xml = xmlhttp.responseXML;
  36.             dato = xml.getElementsByTagName("datos");
  37.             if (dato[0].firstChild.nodeValue == "1") {
  38.                 num_user = xml.getElementsByTagName("numusuario");
  39.  
  40.                 document.getElementById("movil").value = xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  41.                 document.getElementById("calle").value = xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  42.                 document.getElementById("dni").value = xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  43.                 document.getElementById("name").value = xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  44.                 document.getElementById("edificio").value = xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  45.                 document.getElementById("numero").value = xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  46.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  47.                 document.getElementById("piso").value = xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  48.                 document.getElementById("letra").value = xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  49.                 document.getElementById("localidad").value = xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  50.                 document.getElementById("provincia").value = xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  51.                 document.getElementById("email").value = xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  52.             }
  53.            
  54.             if(dato[0].firstChild.nodeValue=="0")
  55.                 envia();
  56.         }, 3500);
  57.     }
  58. }
  59.     }
  60.    
  61. }



He puesto un alert y no me lo hace:

Código Javascript:
Ver original
  1. if (xmlhttp.readyState < 4) {
  2.  
  3.     alert('hola');
  4.     document.getElementById("carga1").innerHTML = "<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  5.  
  6.    
  7. }
  #4 (permalink)  
Antiguo 20/01/2014, 10:17
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Problema con estado 1 en loader

Creo que te faltó el evento onreadystatechange. Yo lo hago así:

Código Javascript:
Ver original
  1. xmlhttp.onreadystatechange = function(){
  2.     if (xmlhttp.readyState < 4){
  3.         //Muestro el gif de carga
  4.     }
  5.     else {
  6.         if (xmlhttp.status == 200){
  7.             //Proceso la respuesta del servidor
  8.         }
  9.         else if (xmlhttp.status == 400){
  10.             //Muestro un mensaje de error
  11.         }
  12.     }
  13. }

Adecua esto a tu código, saludos.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #5 (permalink)  
Antiguo 20/01/2014, 13:02
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Cita:
Iniciado por Alexis88 Ver Mensaje
Creo que te faltó el evento onreadystatechange. Yo lo hago así:

Código Javascript:
Ver original
  1. xmlhttp.onreadystatechange = function(){
  2.     if (xmlhttp.readyState < 4){
  3.         //Muestro el gif de carga
  4.     }
  5.     else {
  6.         if (xmlhttp.status == 200){
  7.             //Proceso la respuesta del servidor
  8.         }
  9.         else if (xmlhttp.status == 400){
  10.             //Muestro un mensaje de error
  11.         }
  12.     }
  13. }

Adecua esto a tu código, saludos.

Perdona pero sigue sin funcionar. He puesto alert y no saltan ninguno:

Código Javascript:
Ver original
  1. function valida_envia(){
  2.  
  3.     var telefonos = document.forms['datos'].elements['telefonos'];
  4.     if (telefonos.value.length == 0)
  5.     {
  6.        
  7.         alert("Insertar el nº de teléfono");
  8.  
  9.         telefonos.focus();
  10.  
  11.         return 0;
  12.  
  13.     }
  14.     else
  15.     {
  16.        
  17.         if (window.XMLHttpRequest)
  18.         {
  19.             xmlhttp=new XMLHttpRequest();
  20.         }
  21.         else
  22.         {
  23.             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  24.         }  
  25.         xmlhttp.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  26.         xmlhttp.send();
  27.        
  28.        
  29.         xmlhttp.onreadystatechange = function(){
  30.         if (xmlhttp.readyState < 4){
  31.            
  32.             alert('gif');
  33.         //Muestro el gif de carga
  34.         }
  35.         else {
  36.          if (xmlhttp.readyState==4 && xmlhttp.status==200){
  37.            
  38.             alert('carga');
  39.        
  40.           var xml = xmlhttp.responseXML;
  41.             dato = xml.getElementsByTagName("datos");
  42.             if (dato[0].firstChild.nodeValue == "1") {
  43.                 num_user = xml.getElementsByTagName("numusuario");
  44.  
  45.                 document.getElementById("movil").value = xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  46.                 document.getElementById("calle").value = xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  47.                 document.getElementById("dni").value = xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  48.                 document.getElementById("name").value = xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  49.                 document.getElementById("edificio").value = xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  50.                 document.getElementById("numero").value = xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  51.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  52.                 document.getElementById("piso").value = xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  53.                 document.getElementById("letra").value = xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  54.                 document.getElementById("localidad").value = xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  55.                 document.getElementById("provincia").value = xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  56.                 document.getElementById("email").value = xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  57.                
  58.                   }
  59.         else if (xmlhttp.status == 400){
  60.            
  61.             alert('error');
  62.             //Muestro un mensaje de error
  63.         }
  64.     }
  65. }
  66.        
  67.           if(dato[0].firstChild.nodeValue=="0")
  68.             {                  
  69.                   envia();  
  70.                          }
  71.                          else{
  72.             }
  73.         }
  74.        
  75.     }
  76.    
  77. }
  #6 (permalink)  
Antiguo 20/01/2014, 15:34
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Problema con estado 1 en loader

¿Pero se está ejecutando la petición asíncrona (Ajax)?
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #7 (permalink)  
Antiguo 20/01/2014, 16:46
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Cita:
Iniciado por Alexis88 Ver Mensaje
¿Pero se está ejecutando la petición asíncrona (Ajax)?
Si, y también hay respuesta ok del php.

Código Javascript:
Ver original
  1. GET http://val_telef.php?telefonos=123135435     200 OK   854ms

Tengo otro código y funciona perfectamente, pero no se como adaptarlo a este:

Código Javascript:
Ver original
  1. $.ajax({
  2. data: $("#frm_filtro").serialize()+ordenar,
  3. type: "POST",
  4. dataType: "json",
  5. url: "ajax.php?action=listar",
  6. beforeSend:function(){
  7. $('.carga1').css('display','block');
  8. $('.carga1').html("<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...");
  9.     },  
  10. complete: function() {
  11.  
  12. $(".carga1").show();
  13. $(".carga1").hide();
  14.  
  15.     },
  16.  success: function(data){
  17.  var html_user ='' ;
  18.  if(data.length > 0){
  19.  $.each(data, function(i,item){
  20.  
  21. html_user += '<tr onclick="pulsar1(this, ' + *String.fromCharCode(39) + item.id_aviso + String.fromCharCode(39) *+ ');"     ondblclick="pulsar(this, ' +  String.fromCharCode(39) + item.id_aviso + String.fromCharCode(39) *+ ');" >';
  22. html_user += '<td><input name="demo" type="checkbox" value="' + item.id_aviso + '"/></td>';
  23.  html_user += '<td>'+item.id_aviso+'</td>';
  24.  html_user += '<td>'+item.telefonos+'</td>';
  25.  html_user += '<td>'+item.name+' '+item.apellidos+'</td>';
  26.  html_user += '<td>'+item.calle+'</td>';
  27.  html_user += '<td>'+item.localidad+'</td>';
  28.  html_user += '<td>'+item.aparatos+'</td>';
  29.  html_user += '<td>'+item.marcas+'</td>';
  30.  html_user += '<td>'+item.facturacion+'</td>';
  31.  html_user += '</tr>';
  32.  
  33.  
  34.      });
  35.   }
  #8 (permalink)  
Antiguo 20/01/2014, 18:11
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Problema con estado 1 en loader

Si mal no recuerdo, es el código de un usuario al que ayudé no hace mucho.

Si trabajas con el método Ajax de jQuery, este tema del gif de carga se te hará muy fácil de resolver. Un pequeñísimo ejemplo:

Código Javascript:
Ver original
  1. $("#miFormulario").submit(function(event){
  2.     event.preventDefault();
  3.     $.ajax({
  4.         url: $(this).prop("action"),
  5.         type: $(this).prop("method"),
  6.         data: $(this).serialize(),
  7.         success: function(response){
  8.             $("#divRespuesta").html(response);
  9.         }
  10.     });
  11. });
  12.  
  13. $(document).ajaxStart(function(){
  14.     $("#divRespuesta").fadeOut(50);
  15.     $("#gifCargando").fadeIn(800);
  16. }).ajaxStop(function(){
  17.     $("#divRespuesta").fadeIn(800);
  18.     $("#gifCargando").fadeOut(800);
  19. });

Básicamente, envío los datos de un formulario mediante una petición asíncrona con Ajax. Cuando se ejecute el método Ajax en el documento, sea con el envío de datos de dicho formulario o desde otra función, se ejecuta el método ajaxStart, mediante el cual, mostraremos el Gif de carga y ocultaremos el Div en donde se mostrará la respuesta de la petición asíncrona. Cuando acabe de ejecutarse la petición, se ejecuta el método ajaxStop, mediante el cual, realizaremos la operación inversa a lo que hicimos cuando inició el proceso con Ajax, es decir, oculto el Gif de carga y muestro del Div de la respuesta. Con los métodos fadeIn y fadeOut, muestro y oculto elementos, respectivamente, en donde los números que indico entre paréntesis, indican el tiempo que durará la transición de la ejecución de cada método.

Para que veas esto en ejecución, puedes ver esta página que hice de ejemplo, los enlaces cargan con Ajax y en cada carga, aparece el Gif de carga: http://orion.byethost24.com/zarai

Saludos
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #9 (permalink)  
Antiguo 20/01/2014, 18:19
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Cita:
Iniciado por Alexis88 Ver Mensaje
Si mal no recuerdo, es el código de un usuario al que ayudé no hace mucho.

Si trabajas con el método Ajax de jQuery, este tema del gif de carga se te hará muy fácil de resolver. Un pequeñísimo ejemplo:

Código Javascript:
Ver original
  1. $("#miFormulario").submit(function(event){
  2.     event.preventDefault();
  3.     $.ajax({
  4.         url: $(this).prop("action"),
  5.         type: $(this).prop("method"),
  6.         data: $(this).serialize(),
  7.         success: function(response){
  8.             $("#divRespuesta").html(response);
  9.         }
  10.     });
  11. });
  12.  
  13. $(document).ajaxStart(function(){
  14.     $("#divRespuesta").fadeOut(50);
  15.     $("#gifCargando").fadeIn(800);
  16. }).ajaxStop(function(){
  17.     $("#divRespuesta").fadeIn(800);
  18.     $("#gifCargando").fadeOut(800);
  19. });

Básicamente, envío los datos de un formulario mediante una petición asíncrona con Ajax. Cuando se ejecute el método Ajax en el documento, sea con el envío de datos de dicho formulario o desde otra función, se ejecuta el método ajaxStart, mediante el cual, mostraremos el Gif de carga y ocultaremos el Div en donde se mostrará la respuesta de la petición asíncrona. Cuando acabe de ejecutarse la petición, se ejecuta el método ajaxStop, mediante el cual, realizaremos la operación inversa a lo que hicimos cuando inició el proceso con Ajax, es decir, oculto el Gif de carga y muestro del Div de la respuesta. Con los métodos fadeIn y fadeOut, muestro y oculto elementos, respectivamente, en donde los números que indico entre paréntesis, indican el tiempo que durará la transición de la ejecución de cada método.

Para que veas esto en ejecución, puedes ver esta página que hice de ejemplo, los enlaces cargan con Ajax y en cada carga, aparece el Gif de carga: http://orion.byethost24.com/zarai

Saludos
Ok, si soy yo mismo, pero Alexis como lo adapto al código del principio del post
  #10 (permalink)  
Antiguo 20/01/2014, 19:14
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Problema con estado 1 en loader

Lo del método Ajax, lo puedes hacer como lo hiciste la vez anterior o de la forma en como lo explico, lo importante en este caso son los métodos ajaxStart y ajaxStop para el tema del Gif de carga.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #11 (permalink)  
Antiguo 21/01/2014, 02:16
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Cita:
Iniciado por Alexis88 Ver Mensaje
Lo del método Ajax, lo puedes hacer como lo hiciste la vez anterior o de la forma en como lo explico, lo importante en este caso son los métodos ajaxStart y ajaxStop para el tema del Gif de carga.
Ya pero porque no funciona el (xmlhttp.readyState==1), y el (xmlhttp.readyState==4) funciona perfectamente. Esa era la primera consulta. No lo entiendo

Esta parte es la que debería de funcionar no ?

Código Javascript:
Ver original
  1. xmlhttp.onreadystatechange=function()
  2.   {
  3.   if (xmlhttp.readyState==1){
  4.     document.getElementById("carga1").innerHTML="<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  5.   }
  6.   else if (xmlhttp.readyState==4 && xmlhttp.status==200)
  7.     {
  8.     document.getElementById("carga1").innerHTML="<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando";
  9.     }
  10.   }
  11. xmlhttp.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  12. xmlhttp.send();

Gracias por tu ayuda

Última edición por satjaen; 21/01/2014 a las 02:48
  #12 (permalink)  
Antiguo 21/01/2014, 09:18
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Problema con estado 1 en loader

Supongo que es por lo que te dije, que la respuesta del servidor se produce tan rápido que no le da tiempo a tu gif de mostrarse, por eso te sugerí que retrases la ejecución de las instrucciones cuando readyState sea igual a 4. A mi me funcionó.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #13 (permalink)  
Antiguo 21/01/2014, 09:54
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Cita:
Iniciado por Alexis88 Ver Mensaje
Supongo que es por lo que te dije, que la respuesta del servidor se produce tan rápido que no le da tiempo a tu gif de mostrarse, por eso te sugerí que retrases la ejecución de las instrucciones cuando readyState sea igual a 4. A mi me funcionó.
No Alexis de la rapidez del servidor no es porque a veces tarda hasta 8 segundos en hacer la búsqueda. Además al poner un alert debería de hacerlo no ?
  #14 (permalink)  
Antiguo 21/01/2014, 09:57
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Problema con estado 1 en loader

Lo mismo creí al inicio, hasta que implementé el cambio del que te cuento y todo marcha como quiero.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #15 (permalink)  
Antiguo 21/01/2014, 11:05
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Cita:
Iniciado por Alexis88 Ver Mensaje
Lo mismo creí al inicio, hasta que implementé el cambio del que te cuento y todo marcha como quiero.
Pero entonces como podemos saber en mi código cuando está en estado 1 ?
  #16 (permalink)  
Antiguo 21/01/2014, 11:10
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Problema con estado 1 en loader

Lo que haces está bien, por eso te digo que implementes lo del retardo de las acciones cuando el estado sea igual a 4, o sino, hazlo con Ajax de jQuery, utilizando los método ajaxStart y ajaxStop, tal y como te lo indiqué más arriba.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #17 (permalink)  
Antiguo 21/01/2014, 11:15
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Cita:
Iniciado por Alexis88 Ver Mensaje
Lo que haces está bien, por eso te digo que implementes lo del retardo de las acciones cuando el estado sea igual a 4, o sino, hazlo con Ajax de jQuery, utilizando los método ajaxStart y ajaxStop, tal y como te lo indiqué más arriba.
Ok, gracias pero por favor me ayudas a hacerlo con ajax o jQuery ?
  #18 (permalink)  
Antiguo 21/01/2014, 17:19
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

Ya lo he resuelto, lo comparto para los que como yo están empezando en este maravilloso mundo. A ver como lo veis, si se puede mejorar por favor decirmelo:

Código Javascript:
Ver original
  1. function valida_envia(e)
  2. {
  3.   if (window.event)
  4.     window.event.returnValue=false;
  5.   else
  6.     if (e)
  7.       e.preventDefault();
  8.   enviarFormulario();
  9. }
  10.  
  11. var conexion1;
  12. function enviarFormulario()
  13. {
  14.   conexion1=crearXMLHttpRequest()
  15.   conexion1.onreadystatechange = procesarEventos;
  16.   var telefonos = document.forms['datos'].elements['telefonos'];
  17.   alert('Valor de la propiedad readyState:'+conexion1.readyState);
  18.   conexion1.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  19.   conexion1.send(null);  
  20. }
  21.  
  22.         function procesarEventos()
  23.         {
  24.         alert('Valor de la propiedad readyState:'+conexion1.readyState);
  25.         var resultados = document.getElementById("carga1");
  26.         if(conexion1.readyState == 4)
  27.         {
  28.         resultados.innerHTML = conexion1.responseText;
  29.        
  30.    
  31.        
  32.          var xml = conexion1.responseXML;
  33.             dato=xml.getElementsByTagName("datos");
  34.             if(dato[0].firstChild.nodeValue=="1")
  35.             {
  36.                 num_user=xml.getElementsByTagName("numusuario");
  37.                
  38.                
  39.                 document.getElementById("movil").value =xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  40.                 document.getElementById("calle").value =xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  41.                 document.getElementById("dni").value =xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  42.                 document.getElementById("name").value =xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  43.                 document.getElementById("edificio").value =xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  44.                 document.getElementById("numero").value =xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  45.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  46.                 document.getElementById("piso").value =xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  47.                 document.getElementById("letra").value =xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  48.                 document.getElementById("localidad").value =xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  49.                 document.getElementById("provincia").value =xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  50.                 document.getElementById("email").value =xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  51.                
  52.            
  53.                  
  54.        
  55.             }
  56.    
  57.         }
  58.         else
  59.         if (conexion1.readyState==1 || conexion1.readyState==2 || conexion1.readyState==3)
  60.         {
  61.         resultados.innerHTML = "<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  62.            }
  63.         }
  64.      
  65.  
  66.     function crearXMLHttpRequest()
  67. {
  68.   var xmlHttp=null;
  69.   if (window.ActiveXObject)
  70.     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  71.   else
  72.     if (window.XMLHttpRequest)
  73.       xmlHttp = new XMLHttpRequest();
  74.   return xmlHttp;
  75. }


Gracias
  #19 (permalink)  
Antiguo 22/01/2014, 06:19
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Problema con estado 1 en loader

He probado y funciona perfecto en Firefox, pero en Chrome no sale la imagen de cargando.......

Alguna idea ?

Etiquetas: ajax, estado, html, loader, 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 03:48.