2012-09-23 58 views
0

我正面臨一個問題。
我已經編寫了用於驗證我的輸入字段的代碼,並對其進行了測試,結果工作正常。然後我實現了使用Jquery Ajax post進行表單提交。現在我的問題是,當我點擊提交按鈕時,我以前實現的驗證功能不再被調用。沒有驗證。它正在提交表單。以下是我的JS代碼。感謝您的幫助Jquery表單驗證不能與Ajax一起使用提交

$(document).ready(function(){ 

     $('#incForm input').mouseover(function() 
     { 
      $(this).popover('show') 
     }); 
     $('#incForm input').mouseout(function() { 
     $(this).popover('hide') 
    });   

    $('form').validate({ 
     rules: { 
     problemId: { 
      required: true 
     }, 
     problemType: { 
      required: true 
     } 
     }, 

     showErrors: function(errorMap, errorList) { 

      $.each(this.successList , function(index, value) { 
       $(value).popover('hide'); 
       $(value).parents('.control-group').removeClass('error'); 
        $(value).parents('.control-group').addClass('success'); 
      }); 

      $.each(errorList , function(index, value) { 
       var _popover = $(value.element).popover({ 
        trigger: 'manual', 
        placement: 'top', 
        content: value.message, 
        template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><div class="popover-content"><p></p></div></div></div>' 
       }); 

       _popover.data('popover').options.content = value.message; 
       $(value.element).parents('.control-group').addClass('error'); 
       $(value.element).popover('show'); 

      }); 
     } 


    });   
    //if submit button is clicked 
    $('#submit').click(function() {  

     //show the loading sign 
     $('#btSpModal').modal('show') ; 
     $('.loading').show(); 


     //start the ajax 
     $.ajax({ 
      //this is the php file that processes the data and send mail 
      url: "/~xrenpill/mvc/process_form.php", 

      //GET method is used 
      type: "POST", 

      data: $("#incForm").serialize(), 
      //Do not cache the page 
      cache: false, 

      //success 
      success: function (html) {    
       //if process.php returned 1/true (send mail success) 
       $('#btdpModal').modal('hide') ; 
       $('.loading').hide(); 
       if (html==1) {     
        //hide the form 
        $('.form').fadeOut('slow');     

        //show the success message 
        $('.done').fadeIn('slow'); 

       //if process.php returned 0/false (send mail failed) 
       } else alert('Sorry, unexpected error. Please try again later.');    
      }  
     }); 

     //cancel the submit button default behaviours 
     return false; 
    });   
    }); 
+0

驗證和Ajax提交發生在同一時間。你需要先確認,如果沒有錯誤,那麼你應該提交表格。 –

+0

你能提供一些樣品嗎? – Codemator

回答

2

使用這樣的事情:

$('#submit').click(function (e){ 
    e.preventDefault(); 
    if(!$("form").valid()) return; 

    ... 
}); 
+0

感謝Man ..它完成了工作.. :) – Codemator