【问题标题】:Validate forms with ajax使用 ajax 验证表单
【发布时间】:2016-08-27 00:53:04
【问题描述】:

我正在使用 ajax 验证表单,但验证后,警报消息不起作用。我不知道问题出在.done (Jquery) 还是 PHP 页面的功能上。

我希望你能帮助我。

HTML(crform21、crform22、crform23、crform44...)

   <form class="formus" id="crform21" name="crform21" method="post">
                <div class="crintro">Hola <strong>Fast</strong>, estás a punto de enviar una Cita Rápida a <strong>Maiers</strong> , rellena todos los campos y cruza los dedos para que 
                acepte. Hoy puede ser un Gran Día!</div><br>
                <h6><i class="icon-home"></i> Lugar de la Cita*</h6>
                <input type="text" value="" maxlength="250" name="crsite" id="crsite">
                <div id="addr">
                    <div style="width: 50%">
                <h6><i class="icon-home"></i> Calle*</h6>
                <input type="text" value="" maxlength="250" name="crstreet" id="crstreet">
                    </div>
                    <div style="width: 50%">
                <h6> Número</h6>
                <input type="text" value="" maxlength="10" name="crnumber" id="crnumber">
                    </div>
                </div>
                <h6><i class="icon-home"></i> Ciudad*</h6>
                <input type="text" value="" maxlength="250" name="crcity" id="crcity">
                <h6><i class="icon-home"></i> Código Postal</h6>
                <input type="text" value="" maxlength="250" name="crcpostal" id="crcpostal">
                <h6><i class="icon-calendar"></i> Fecha de la cita (DD-MM-AAAA HH:mm)*</h6>
                <input type="text" name="crfecha" id="crfecha" class="datepicker">
                <h6><i class="icon-lock"></i> Palabra secreta*</h6>
                <input type="text" value="" maxlength="250" name="crsecret" id="crsecret">
                <h6><i class="icon-comments"></i> Plan de la cita</h6>      
                <textarea rows="3" cols="20" name="crcomentario" id="crcomentario"></textarea><br>
                <input type="hidden" value="21" name="idreceptor">
                <input type="hidden" value="1" name="idcitador">
                <input type="hidden" value="Maiers" name="namereceptor">
                <input type="hidden" value="Fast" name="namecitador">
                <input type="hidden" value="http://www.fastdate.es/profile/easyloveadmin/" name="urlcitador">
                <input type="submit" value="Enviar cita" data-id="21" class="rating-button">
                </form>

PHP

//Si no se han rellenado todos los datos obligatorios o se intenta acceder al archivo sin estar logueado

 if(empty($lugar)){
     $errores['lugar'] ='Tienes que introducir un lugar para la cita';
 }
  if(empty($calle)){
     $errores['calle'] ='Tienes que introducir una calle para la cita';
 }
  if(empty($ciudad)){
     $errores['ciudad'] ='Tienes que introducir una ciudad';
 }
  if(empty($fecha)){
     $errores['fecha'] ='Tienes que introducir una fecha';
 }
  if(empty($pass)){
     $errores['pass'] ='Tienes que introducir una palabra secreta';
 }

if(empty($errores)){


    //Conexión Base de Datos

    include('conexion.php');

    //Guardamos la cita

    $grabarcita = mysql_query (
    "INSERT INTO wp_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_status, comment_status, ping_status, post_password, post_name, post_parent, menu_order, post_type) " .
    "VALUES ('$citador','$hoy', '$hoy', '$contenido', '$title', '$publish', '$comment', '$pingst', '$pass', '$pname', '$parent', '$order', '$type')") or die (mysql_error());

    $grabarcitatabla = mysql_query (
    "INSERT INTO wp_citas (citador, idcitador, receptor,idreceptor, fecha, nomcita, passpriv, urlcita, estado, fechacita) " .
    "VALUES ('$namecitador','$citador', '$namereceptor', '$receptor', '$hoy', '$title', '$pass', '$urlcita', '$status', '$fecha')") or die (mysql_error());

    $datos['exito'] = true;
    $datos['mensaje'] = 'El registro se ha realizado correctamente.';

    //Enviamos Email de alerta de la cita a la persona citada

    include('sendmail.php');

    //Se cierra conexión con la Base de Datos

    mysql_close($link);

}else{
    $datos['exito'] = false;
    $datos['errores'] = $errores;
}

//Dar respuesta

 echo json_encode($datos);

我有这个但是函数.done不起作用:

jQuery(document).ready(function($){

        var form = $('.formus');

        var url = '/controladores/grabarcita.php';

        var data = form.serialize();


    $(form).on('submit', function(e){
        e.preventDefault();  

        $.post(url, $(this).serialize(), function(result){

        if(result.exito){
            alert("yes");
        }else{
            alert("no");
        }
        }).fail(function() {
            alert( "error" );
        });

   });
}); 

【问题讨论】:

  • 欢迎来到Stackoverflow..这里一定要加英文问题.....
  • 嗨,karan,当我发送数据并进行验证时,现在我总是收到“否”的警报,但它没有运行任何错误。有什么想法吗?
  • 你好费尔南多。您是否看到存在一个名为 Stack Overflow en español 的 Stack Exchange 站点,它完全致力于西班牙语?
  • Bobulous 我不知道,谢谢!

标签: php jquery ajax forms validation


【解决方案1】:

似乎data 获得了错误的值,因为您在表单处理程序之外对其进行了初始化,因此您将所有表单数据发送到您的 php 文件。尝试序列化您正在处理的表单(在 onSubmit 处理程序中使用$(this).serialize())并将其用作数据:

$(form).on('submit', function(e){
        e.preventDefault();  

        $.ajax({        
        type    : 'POST',
        url     : url,
        // make sure you're sending this form's data!
        data    : $(this).serialize(),
        dataType: 'json',
        encode  : true      
        })  
        .done(function(datos){
        //Especificamos las respuestas para los datos recibidos
        if(datos.exito){
            alert(datos.mensaje);
        }else{
            if(datos.errores.lugar){
                alert(datos.errores.lugar);
            }
            if(datos.errores.calle){
                alert(datos.errores.calle);
            }
        }

        });

    });

现在您应该发送适当的数据了。否则逻辑似乎是合理的,虽然我没有测试它。

祝你好运!

【讨论】:

  • 感谢 derelict,现在我正在发送要验证的正确数据,这是输出:{"exito":false,"errores":{"lugar":"Tienes que introducir un lugar para la cita","calle":"Tienes que introducir una calle para la cita","ciudad":"Tienes que introducir una ciudad","pass":"Tienes que introducir una palabra secreta","plancita":"Tienes que tener un plan para tu cita"}} 但是代码的第二部分不起作用,带有消息的警报不起作用,你知道为什么吗?谢谢
  • 看起来不错,在您的 .done() 处理程序中尝试 console.log(datos) 以确保 jquery 正确解析您的响应,并查看浏览器控制台中的网络流量以确保响应正文有正确的类型和内容——如果它仍然是个谜,可能是时候提出一个新问题了:)
  • 是的,我已经更改了问题的标题,我没有看到问题并且看起来没问题,但我想它可能在 PHP 文件中。我尝试其他方法但没有。无论如何,谢谢。
【解决方案2】:

我忘记了函数中的数据类型“json”:

jQuery(document).ready(function($){

        var form = $('.formus');

        var url = '/controladores/grabarcita.php';

        var data = form.serialize();


    $(form).on('submit', function(e){
        e.preventDefault();  

        $.post(url, $(this).serialize(), function(result){

        if(result.exito == true){
            alert(result.mensaje);
        }else{
            alert("no");
        }
        },'json').fail(function() {
            alert( "error" );
        });

   });
}); 

现在可以了!谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    相关资源
    最近更新 更多