weixin_33712987 2016-08-27 00:53 采纳率: 0%
浏览 41

使用ajax验证表单

I'm validating forms with ajax, but after validation, the alerts messages don't work. I don't know if the problem is in function the .done (Jquery) or the PHP page.

I hope you can help me.

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);

I have this but function .done does not work:

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" );
        });

   });
}); 
  • 写回答

2条回答 默认 最新

  • weixin_33709609 2016-08-27 01:05
    关注

    it appears as though data gets the wrong value, because you initialize it outside your form handler, so you you're sending all form data to your php file. try instead serializing the form you're processing (using $(this).serialize() in the onSubmit handler) and using that as data:

    $(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);
                }
            }
    
            });
    
        });
    

    now you should be sending the appropriate data over. otherwise the logic seems sound, although i didn't test it.

    good luck!

    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站