Foros del Web » Programando para Internet » Jquery »

ajax captcha jquery

Estas en el tema de ajax captcha jquery en el foro de Jquery en Foros del Web. Holas comunidad, quisiera ayuda, si no es molestia :D, con el siguiente problema: - Tengo un formulario para enviar un correo a cierta dirección mediante ...
  #1 (permalink)  
Antiguo 14/06/2012, 09:13
Avatar de SnakeCode  
Fecha de Ingreso: mayo-2012
Ubicación: Lima - Perú
Mensajes: 23
Antigüedad: 12 años
Puntos: 1
ajax captcha jquery

Holas comunidad, quisiera ayuda, si no es molestia :D, con el siguiente problema:

- Tengo un formulario para enviar un correo a cierta dirección mediante la web. Y tengo el captcha, como he leído en varios temas, la validación del captcha se tiene que realizar dentro del servidor, ahí todo bien .... pero quisiera que si escribo mal el captcha me envíe un mensaje que esta mal escrito al mismo formulario y sino envíe el correo con normalidad, y quisiera hacerlo con el método ajax de jquery, si me entienden espero una ayuda lo más pronto. Gracias de antemano. Saludos
  #2 (permalink)  
Antiguo 15/06/2012, 09:15
Avatar de maycolalvarez
Colaborador
 
Fecha de Ingreso: julio-2008
Ubicación: Caracas
Mensajes: 12.120
Antigüedad: 15 años, 9 meses
Puntos: 1532
Respuesta: ajax captcha jquery

eso debe hacerlo en el mismo servidor, cuando valide el captcha vuelque dicho mensaje, no depende de javascript.

Le advierto que no es recomendable la validación de un captcha por medio de ajax para luego enviar la data del formulario, debe de enviarlo TODO de una vez y validar el captcha y la data al mismo tiempo, no validar el captcha en una petición y enviar la data por otra, todo debe hacerse dentro de una misma petición HTTP, así sea por ajax
__________________
¡Por favor!: usa el highlight para mostrar código
El que busca, encuentra...
  #3 (permalink)  
Antiguo 15/06/2012, 10:34
Avatar de SnakeCode  
Fecha de Ingreso: mayo-2012
Ubicación: Lima - Perú
Mensajes: 23
Antigüedad: 12 años
Puntos: 1
Respuesta: ajax captcha jquery

Cita:
Iniciado por maycolalvarez Ver Mensaje
eso debe hacerlo en el mismo servidor, cuando valide el captcha vuelque dicho mensaje, no depende de javascript.

Le advierto que no es recomendable la validación de un captcha por medio de ajax para luego enviar la data del formulario, debe de enviarlo TODO de una vez y validar el captcha y la data al mismo tiempo, no validar el captcha en una petición y enviar la data por otra, todo debe hacerse dentro de una misma petición HTTP, así sea por ajax
Hola y gracias por tu respuesta, yo estoy enviando todos los datos al servidor por medio del método $.ajax, lo que pretendo es que cuando, se ha escrito mal el captcha me mande un mensaje que diga: "Error en el codigo captcha" y recarge la imagen del captcha por otra.

Aquí esta el código:

Código Javascript:
Ver original
  1. $(document).ready(function(){
  2.        
  3.         /************************************* CALENDARIO JQUERY UI ******************************************/
  4.         $("#Fecha").datepicker({
  5.             showOn: 'both',
  6.             buttonImage: 'imagenes/calendario.gif',
  7.             buttonImageOnly: true
  8.         });
  9.         /******************************************************************************************************************/
  10.        
  11.         /************************************* VALIDACION DE FORMULARIOS *************************************************/
  12.         var correo = /^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/;
  13.        
  14.         $("#Submit").click(function(){
  15.        
  16.             $(".error").remove();
  17.  
  18.             if($("#Nombre").val() == ""){
  19.                 $("#Nombre").focus().after('<br /><span class="error">Ingrese su nombre</span>');
  20.                 return false;  
  21.             }else if($("#Pais").val() == ""){
  22.                 $("#Pais").focus().after('<br /><span class="error">Ingrese su pais</span>');
  23.                 return false;
  24.             }else if($("#Correo").val() == "" || !correo.test($("#Correo").val())){
  25.                 $("#Correo").focus().after('<br /><span class="error">Ingrese email valido</span>');   
  26.                 return false;
  27.             }else if($("#captcha").val() == ""){
  28.                 $("#captcha").focus().after('<br /><span class="error">Ingrese los caracteres de la imagen</span>');
  29.                 return false;
  30.             }else{
  31.                 var datos = "Nombre=" + $("#Nombre").val() +
  32.                         "&Pais=" + $("#Pais").val() +
  33.                         "&Telefono=" + $("#Telefono").val() +
  34.                         "&Correo=" + $("#Correo").val() +
  35.                         "&Sexo=" + $("input[name='Sexo']:checked").val() +
  36.                         "&Edad=" + $("#Edad").val() +
  37.                         "&Permanencia=" + $("#Permanencia").val() +
  38.                         "&Fecha=" + $("#Fecha").val() +
  39.                         "&Encontro=" + $("#Encontro").val() +
  40.                         "&Comentarios=" + $("#Comentarios").val() +
  41.                         "&url=" + $("#url").val() +
  42.                         "&captcha=" + $("#captcha").val();
  43.                        
  44.                 $.ajax({
  45.                     type    : 'POST',
  46.                     url     : 'captcha/c-envio-solicitud-2.php',
  47.                     data    : datos,
  48.                     success : function(){
  49.                                    
  50.                               },
  51.                     error   : function(){
  52.                                     alert("No se pudo enviar el mensaje. ¡Intentelo nuavamente!");
  53.                               }
  54.                 });
  55.                 return false;
  56.             }
  57.         });
  58.        
  59.         $("#Nombre, #Pais").keyup(function(){
  60.             if( $(this).val() != "" ){
  61.                 $(".error").fadeOut();
  62.                 return false;
  63.             }
  64.         });
  65.        
  66.         $("#Correo").keyup(function(){
  67.             if( $(this).val() != "" && correo.test($(this).val())){
  68.                 $(".error").fadeOut();
  69.                 return false;
  70.             }
  71.         });
  72.         /**********************************************************************************************************************/
  73.        
  74.         /************************************ REFRESCAR CAPTCHA ***************************************************************/
  75.         $('img#refresh').click(function() {  
  76.               change_captcha();
  77.         });
  78.        
  79.         function change_captcha(){
  80.           document.getElementById('im_captcha').src="captcha/captcha.php?" + Math.random();
  81.         }
  82.         /********************************************************************************************************************/
  83. });
  #4 (permalink)  
Antiguo 15/06/2012, 14:54
Avatar de SnakeCode  
Fecha de Ingreso: mayo-2012
Ubicación: Lima - Perú
Mensajes: 23
Antigüedad: 12 años
Puntos: 1
Respuesta: ajax captcha jquery

Bueno en realidad, ya tengo un script AJAX para el envio pero no me funciona en Chrome, en todos menos en chrome, y es el siguiente:

Código Javascript:
Ver original
  1. var http_request = false;
  2.    var clicks     = 0;
  3.    function makePOSTRequest(url, parameters) {
  4.       http_request = false;
  5.       if (window.XMLHttpRequest) { // Mozilla, Safari,...
  6.          http_request = new XMLHttpRequest();
  7.          if (http_request.overrideMimeType) {
  8.             // set type accordingly to anticipated content type
  9.             //http_request.overrideMimeType('text/xml');
  10.             http_request.overrideMimeType('text/html');
  11.          }
  12.       } else if (window.ActiveXObject) { // IE
  13.          try {
  14.             http_request = new ActiveXObject("Msxml2.XMLHTTP");
  15.          } catch (e) {
  16.             try {
  17.                http_request = new ActiveXObject("Microsoft.XMLHTTP");
  18.             } catch (e) {}
  19.          }
  20.       }
  21.       if (!http_request) {
  22.          alert('Cannot create XMLHTTP instance');
  23.          return false;
  24.       }
  25.      
  26.       http_request.onreadystatechange = alertContents;
  27.       http_request.open('POST', url, true);
  28.       http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  29.       http_request.setRequestHeader("Content-length", parameters.length);
  30.       http_request.setRequestHeader("Connection", "close");
  31.       http_request.send(parameters);
  32.    }
  33.  
  34.    function alertContents() {
  35.       if (http_request.readyState == 4) {
  36.          if (http_request.status == 200) {
  37.             //alert(http_request.responseText);
  38.             result = http_request.responseText;
  39.             document.getElementById('myspan').innerHTML = result;            
  40.          } else {
  41.             alert('Hubo un problema en la Solicitud.');
  42.          }
  43.       }
  44.    }
  45.    
  46.    function get(obj) {
  47.         var varSex="";
  48.           if(document.getElementsByName("Sexo")[0].checked){
  49.                 varSex = document.getElementsByName("Sexo")[0].value;
  50.           }else if(document.getElementsByName("Sexo")[1].checked){
  51.                 varSex = document.getElementsByName("Sexo")[1].value;
  52.             }else{
  53.                 varSex = "";
  54.             }
  55.       var poststr = "Nombre=" + encodeURI( document.getElementById("Nombre").value ) +
  56.             "&Pais=" + encodeURI( document.getElementById("Pais").value ) +
  57.             "&Telefono=" + encodeURI( document.getElementById("Telefono").value )+
  58.             "&Correo=" + encodeURI( document.getElementById("Correo").value )+
  59.             "&Sexo=" + encodeURI(varSex) +
  60.             "&Edad=" + encodeURI( document.getElementById("Edad").value )+
  61.             "&Permanencia=" + encodeURI( document.getElementById("Permanencia").value )+
  62.             "&Fecha=" + encodeURI( document.getElementById("Fecha").value )+
  63.             "&Encontro=" + encodeURI( document.getElementById("Encontro").value )+
  64.             "&Comentarios=" + encodeURI( document.getElementById("Comentarios").value )+
  65.             "&url=" + encodeURI( document.getElementById("url").value )+
  66.             "&capt=" + encodeURI( document.getElementById("capt").value )+           
  67.             "&Submit=" + encodeURI( document.getElementById("Submit").value );
  68.       makePOSTRequest('http://www.vivatoursperu.com/captcha/c-envio-solicitud.php', poststr);
  69.    }
  70.  
  71.    function write_captcha(){
  72.         define('Nombre', 'string', 'Nombre');
  73.         define('Correo', 'email', 'E-mail');
  74.         define('Pais', 'string', 'País');
  75.         define('capt', 'string', 'Captcha');
  76.     clicks++;
  77.     document.getElementById('capt').value       = ''
  78.       document.getElementById('captcha_id').innerHTML = '<img src="http://www.vivatoursperu.com/captcha/captcha_img.php?clicks=' + clicks + '" border="0" alt="" /><a href="#" onclick="write_captcha();"><img src="http://www.vivatoursperu.com/captcha/png_bank/refresh.gif" border="0" alt="" /></a><br />Escribe los caracteres de la imagen';
  79.    return false;
  80.    }

Por tal razon, queria hacerlo con jquery para ver si funciona pero en realidad no se como =S, este es el codigo modificado:

Código Javascript:
Ver original
  1. var clicks    = 0;
  2.    function makePOSTRequest(datos) {
  3.         $.ajax({
  4.                     type        : 'POST',
  5.                     dataType    : 'html',
  6.                     contentType : 'application/x-www-form-urlencoded',
  7.                     url         : 'captcha/c-envio-solicitud.php',
  8.                     data        : datos,
  9.                     success     : datos_enviados,
  10.                     timeout     : 4000,
  11.                     error       : problemas
  12.                 });  
  13.    }
  14.    
  15.    function datos_enviados(){
  16.        $("#myspan").text(datos);
  17.    }
  18.    
  19.    function problemas(){
  20.        alert("Problemas en el servidor...");
  21.    }
  22.    
  23.    function get(obj) {
  24.         var varSex="";
  25.           if(document.getElementsByName("Sexo")[0].checked){
  26.                 varSex = document.getElementsByName("Sexo")[0].value;
  27.           }else if(document.getElementsByName("Sexo")[1].checked){
  28.                 varSex = document.getElementsByName("Sexo")[1].value;
  29.             }else{
  30.                 varSex = "";
  31.             }
  32.       var poststr = "Nombre=" + encodeURI( document.getElementById("Nombre").value ) +
  33.             "&Pais=" + encodeURI( document.getElementById("Pais").value ) +
  34.             "&Telefono=" + encodeURI( document.getElementById("Telefono").value )+
  35.             "&Correo=" + encodeURI( document.getElementById("Correo").value )+
  36.             "&Sexo=" + encodeURI(varSex) +
  37.             "&Edad=" + encodeURI( document.getElementById("Edad").value )+
  38.             "&Permanencia=" + encodeURI( document.getElementById("Permanencia").value )+
  39.             "&Fecha=" + encodeURI( document.getElementById("Fecha").value )+
  40.             "&Encontro=" + encodeURI( document.getElementById("Encontro").value )+
  41.             "&Comentarios=" + encodeURI( document.getElementById("Comentarios").value )+
  42.             "&url=" + encodeURI( document.getElementById("url").value )+
  43.             "&capt=" + encodeURI( document.getElementById("capt").value )+           
  44.             "&Submit=" + encodeURI( document.getElementById("Submit").value );
  45.             makePOSTRequest(poststr);
  46.    }
  47.  
  48.    function write_captcha(){
  49.         define('Nombre', 'string', 'Nombre');
  50.         define('Correo', 'email', 'E-mail');
  51.         define('Pais', 'string', 'País');
  52.         define('capt', 'string', 'Captcha');
  53.     clicks++;
  54.     document.getElementById('capt').value       = ''
  55.       document.getElementById('captcha_id').innerHTML = '<img src="http://www.vivatoursperu.com/captcha/captcha_img.php?clicks=' + clicks + '" border="0" alt="" /><a href="#" onclick="write_captcha();"><img src="http://www.vivatoursperu.com/captcha/png_bank/refresh.gif" border="0" alt="" /></a><br />Escribe los caracteres de la imagen';
  56.    return false;
  57.    }

Alguna ayudita urgente, que necesito arreglar ese problema en el trabajo. Gracias de antemano.

PD: el codigo de mi post anterior no es valido, disculpen!!

Saludos

Última edición por SnakeCode; 15/06/2012 a las 15:51
  #5 (permalink)  
Antiguo 18/06/2012, 08:52
Avatar de SnakeCode  
Fecha de Ingreso: mayo-2012
Ubicación: Lima - Perú
Mensajes: 23
Antigüedad: 12 años
Puntos: 1
Respuesta: ajax captcha jquery

Holas comunidad, no se si alguien me puede decir si este codigo javascript con metodo ajax es incompatible con Google Chrome, ya el formulario envía en otro navegadores menos en chrome:

Código Javascript:
Ver original
  1. var http_request = false;
  2.    var clicks     = 0;
  3.    function makePOSTRequest(url, parameters) {
  4.       http_request = false;
  5.       if (window.XMLHttpRequest) { // Mozilla, Safari,...
  6.          http_request = new XMLHttpRequest();
  7.          if (http_request.overrideMimeType) {
  8.             // set type accordingly to anticipated content type
  9.             //http_request.overrideMimeType('text/xml');
  10.             http_request.overrideMimeType('text/html');
  11.          }
  12.       } else if (window.ActiveXObject) { // IE
  13.          try {
  14.             http_request = new ActiveXObject("Msxml2.XMLHTTP");
  15.          } catch (e) {
  16.             try {
  17.                http_request = new ActiveXObject("Microsoft.XMLHTTP");
  18.             } catch (e) {}
  19.          }
  20.       }
  21.       if (!http_request) {
  22.          alert('Cannot create XMLHTTP instance');
  23.          return false;
  24.       }
  25.      
  26.       http_request.onreadystatechange = alertContents;
  27.       http_request.open('POST', url, true);
  28.       http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  29.       http_request.setRequestHeader("Content-length", parameters.length);
  30.       http_request.setRequestHeader("Connection", "close");
  31.       http_request.send(parameters);
  32.    }
  33.  
  34.    function alertContents() {
  35.       if (http_request.readyState == 4) {
  36.          if (http_request.status == 200) {
  37.             //alert(http_request.responseText);
  38.             result = http_request.responseText;
  39.             document.getElementById('myspan').innerHTML = result;            
  40.          } else {
  41.             alert('Hubo un problema en la Solicitud.');
  42.          }
  43.       }
  44.    }
  45.    
  46.    function get(obj) {
  47.         var varSex="";
  48.           if(document.getElementsByName("Sexo")[0].checked){
  49.                 varSex = document.getElementsByName("Sexo")[0].value;
  50.           }else if(document.getElementsByName("Sexo")[1].checked){
  51.                 varSex = document.getElementsByName("Sexo")[1].value;
  52.             }else{
  53.                 varSex = "";
  54.             }
  55.       var poststr = "Nombre=" + encodeURI( document.getElementById("Nombre").value ) +
  56.             "&Pais=" + encodeURI( document.getElementById("Pais").value ) +
  57.             "&Telefono=" + encodeURI( document.getElementById("Telefono").value )+
  58.             "&Correo=" + encodeURI( document.getElementById("Correo").value )+
  59.             "&Sexo=" + encodeURI(varSex) +
  60.             "&Edad=" + encodeURI( document.getElementById("Edad").value )+
  61.             "&Permanencia=" + encodeURI( document.getElementById("Permanencia").value )+
  62.             "&Fecha=" + encodeURI( document.getElementById("Fecha").value )+
  63.             "&Encontro=" + encodeURI( document.getElementById("Encontro").value )+
  64.             "&Comentarios=" + encodeURI( document.getElementById("Comentarios").value )+
  65.             "&url=" + encodeURI( document.getElementById("url").value )+
  66.             "&capt=" + encodeURI( document.getElementById("capt").value )+           
  67.             "&Submit=" + encodeURI( document.getElementById("Submit").value );
  68.       makePOSTRequest('http://www.vivatoursperu.com/captcha/c-envio-solicitud.php', poststr);
  69.    }
  70.  
  71.    function write_captcha(){
  72.         define('Nombre', 'string', 'Nombre');
  73.         define('Correo', 'email', 'E-mail');
  74.         define('Pais', 'string', 'País');
  75.         define('capt', 'string', 'Captcha');
  76.     clicks++;
  77.     document.getElementById('capt').value       = ''
  78.       document.getElementById('captcha_id').innerHTML = '<img src="http://www.vivatoursperu.com/captcha/captcha_img.php?clicks=' + clicks + '" border="0" alt="" /><a href="#" onclick="write_captcha();"><img src="http://www.vivatoursperu.com/captcha/png_bank/refresh.gif" border="0" alt="" /></a><br />Escribe los caracteres de la imagen';
  79.    return false;
  80.    }

Gracias y Saludos!!
  #6 (permalink)  
Antiguo 18/06/2012, 15:06
Avatar de maycolalvarez
Colaborador
 
Fecha de Ingreso: julio-2008
Ubicación: Caracas
Mensajes: 12.120
Antigüedad: 15 años, 9 meses
Puntos: 1532
Respuesta: ajax captcha jquery

ya le indique que dicho mensaje sólo lo puede volcar desde el servidor PHP, por lo tanto debe de verificarlo allí e interceptarlo en el onReadyStateChange de alguna forma, sea devolviendo un JSON o una cadena preformateada.

usted sólo ha publicado el código Javascript y Javascript con jQuery, entienda que así use jQuery no resolverá el requerimiento porque depende del servidor, no del cliente
__________________
¡Por favor!: usa el highlight para mostrar código
El que busca, encuentra...

Etiquetas: ajax, captcha, formulario
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 14:53.