使用记录保存的消息进行表单验证

Form Validation With Record Saved Message

本文关键字:表单 验证 消息 记录 保存      更新时间:2023-09-26

我想知道是否有人能帮我。

首先,我很抱歉,我对JavaScript和jQuery还比较陌生,所以这可能是一个非常愚蠢的问题。

使用这些教程,我把这个页面放在一起,允许用户将记录添加到MySQL数据库中,但我在表单"验证"和jQuery"提交"消息方面遇到了一些困难。

如果使用-选择上面的链接,则页面加载后,选择"保存",您会看到正确的字段验证已激活,但尽管存在验证错误,"位置已保存"消息仍会显示在页面底部,页面会刷新并将记录保存到数据库。

显然,这是不应该发生的,但我在加入"验证"answers"提交"消息时遇到了很大的困难。它们独立地工作得很好,但正如你所看到的,一旦在一起,它们就不会了。

下面的代码处理"保存记录"和页面的刷新

更新-下面的工作解决方案

<script>
        jQuery(document).ready(function(){
            jQuery("#addlocation").validationEngine();
            $("#addlocation").bind("jqv.field.result", function(event, field, errorFound, prompText){ console.log(errorFound) })
        });
    </script>
<script type="text/javascript">
$(document).ready(function(){
    $('#addlocation').submit(function(){
        //check the form is not currently submitting
        if($(this).data('formstatus') !== 'submitting'){
            //setup variables
            var form = $(this),
                formData = form.serialize(),
                formUrl = form.attr('action'),
                formMethod = form.attr('method'), 
                responseMsg = $('#saverecordresponse');
            //add status data to form
            form.data('formstatus','submitting');
            //show response message - waiting
            responseMsg.hide()
                       .addClass('response-waiting')
                       .text('Please Wait...')
                       .fadeIn(200);
            //send data to server for validation
            $.ajax({
                url: formUrl,
                type: formMethod,
                data: formData,
                success:function(data){
                    //setup variables
                    var responseData = jQuery.parseJSON(data), 
                        klass = '';
                    //response conditional
                    switch(responseData.status){
                        case 'error':
                            klass = 'response-error';
                        break;
                        case 'success':
                            klass = 'response-success';
                        break;  
                    }
                    //show reponse message
                    responseMsg.fadeOut(200,function(){
                        $(this).removeClass('response-waiting')
                               .addClass(klass)
                               .text(responseData.message)
                               .fadeIn(200,function(){
                                   //set timeout to hide response message
                                   setTimeout(function(){
                                       responseMsg.fadeOut(200,function(){
                                           $(this).removeClass(klass);
                                           form.data('formstatus','idle');
                                       });
                                   },3000)
                                });
                    });
                }
            });
        }
        //prevent form from submitting
        return false;
    });
});
</script>

这是在选择"保存"按钮时调用的"saverecord.php"脚本。

<?php

    //sanitize data
    $userid = mysql_real_escape_string($_POST['userid']);   
    $locationname = mysql_real_escape_string($_POST['locationname']);   
    $returnedaddress = mysql_real_escape_string($_POST['returnedaddress']); 
    //validate email address - check if input was empty
    if(empty($locationname)){
        $status = "error";
        $message = "You didn't enter a name for this location!";
    }
    else if(!preg_match('/^$|^[A-Za-z0-9 _.,]{5,35}$/', $locationname)){ //validate email address - check if is a valid email address
            $status = "error";
            $message = "You have entered an invalid Location Name!";
    }
    else{
            $query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress) VALUES ('$userid', '$locationname', '$returnedaddress')");  
            if($query){ //if insert is successful
                $status = "success";
                $message = "Location Saved!";   
            }
            else { //if insert fails
                $status = "error";
                $message = "I'm sorry, there has been a technical error! Please try again. If problems persist please contact Map My Finds support.";   
            }
    }
    //return json response
    $data = array(
        'status' => $status,
        'message' => $message
    );
    echo json_encode($data);
    exit;
?>

我只是想知道是否有人能看看这个,让我知道我哪里错了。

非常感谢并衷心问候

我认为您需要:

if($.validationEngine.submitForm(this,settings) == true) {return false;}

在$.ajax行之前的某个位置

IRHM,在您的活动(即)中提交之前,请检查表单是否已验证

$('#addlocation').submit(function(){
    if($(this).validate()){
       // put your all existing content here.
    }  
});

为了防止在ajax将return false放在if块(即)中的上述脚本末尾后提交表单

if($(this).validate()){
    // put your all existing content here.
    return false;
} 

我想这个问题是由于验证引擎而发生的,所以在这种情况下,为了防止表单提交,请尝试使用以下方法:

$('#addlocation').submit(function(evt){
    if($(this).validate()){
       evt.preventDefault();
       // put your all existing content here.
    }  
});

如果上面的代码不起作用,那么将onValidationComplete事件与validationEngine一起包含,并将If($(this).validate())块的所有现有内容放入其中,即

jQuery(document).ready(function(){
   // binds form submission and fields to the validation engine
   jQuery("#addlocation").validationEngine({ onValidationComplete: function(){ 
        //setup variables
        //add status data to form
        //show response message - waiting
        //send data to server for validation
        return false; 
      }
    });
});

好运

经过几天的工作,我现在通过使用我在原始文章中添加的示例,获得了一个有效的解决方案。