-3

我有一个简单的几个 html 控件的表单。我想在 ajax jquery 中将数据保存到 mysql。但它没有总结它。这是我尝试过的

$('#myForm').ajaxForm({

          beforeSubmit : function() { 

          var lookup          = true;

          var validate        = false;
          $.ajax({

             async: false,

             url: 'user.php?username='+$('#username').val(),

             success: function(data) { }

         })
 validate =  $("#myForm").validate({rules: { price: { number: true, }, size: { number: true, }} , errorClass: 'form_fields_error',  errorPlacement: function(error, element) {}}).form() ;
if(lookup && validate ){

                return true;

            }

            else{

                return true;

            }

          },
       target: '#showdata',

          success: function() { }

        });

      });

    $("#myForm").submit(function()
  {

 alert('this is not fired');
//e.preventDefault();
var formData = $(this).serialize();

$.ajax(
{
    type:'post',
    url:'administration/save_users.php',
    data:formData,
    beforeSend:function()
    {
       // launchpreloader();
    },
    complete:function()
    {
       // stopPreloader();
    },
    success:function(result)
    {
         alert(result);
    }

});

});

表单提交没有被解雇......我错过了什么?我有表单 action="#"....

4

1 回答 1

1

根据您的代码,大概您正在使用jQuery Validate plugin

validate =  $("#myForm").validate({rules: { price: { number: true, }, size: { number: true, }} , errorClass: 'form_fields_error',  errorPlacement: function(error, element) {}}).form() ;

您的代码充满了多次ajax调用和多余的submit处理程序。它格式不佳的事实无助于我们解开和排除故障。

根据 jQuery Validate 文档

submitHandler,回调,默认:默认(本机)表单提交

回调,用于在表单有效时处理实际提交。获取表单作为唯一参数。替换默认提交。验证后通过 Ajax 提交表单的正确位置。

这意味着您应该将您的ajax放在submitHandler插件的回调函数中。

你...

  • 不需要使用submit处理程序(这是内置在插件中的)

  • 在提交/点击之前/期间不需要测试表单的有效性(这也内置在插件中)

尝试这样做...

见演示:http: //jsfiddle.net/zuXYR/

$(document).ready(function () {

    $('#myForm').validate({ // initialize the plugin
        rules: { 
            price: { 
                number: true 
            }, 
            size: { 
                number: true
            }
        }, 
        errorClass: 'form_fields_error',  
        errorPlacement: function(error, element) {
            // return false;  // this will suppress errors
            error.insertAfter(element); // the default function
        },
        submitHandler: function (form) {
            // your ajax code here
            return false; // required when using ajax to prevent a page reload
        }
    });

});

另外,我不确定您为什么希望errorPlacement回调函数为空。如果要抑制错误消息,请使用return false. 否则,如果您想使用默认行为,请errorPlacement完全忽略回调。

于 2013-03-28T23:36:00.883 回答