2011-12-30 68 views
1

我一直用這個例子:http://youhack.me/2010/05/04/username-availability-check-in-registration-form-using-jqueryphp/創建表單(需要用戶確認頁面添加到數據庫之前 - 這來後容易的部分)。不過我會把它想在提交表單之前檢查用戶名是否可用。我不能爲我的生活找不出什麼即時做錯了吧:P用戶名檢查表單提交之前 - JQUERY/AJAX

我的jQuery/AJAX是如下:(它調用PHP文件工作正常,我有沒有必要把它放在這裏)

$(document).ready(function() 
    { 
     $(".form").submit(function() 
     { 
      var username = $(".userID").val(); 

      $.ajax({ 
       type: "POST", 
       url: "id_check.php", 
       data: "userID="+ username, 
       success: function(response){ 

        if(response=="NO"){ 
         alert("no");  
        } 
        else if(response=="YES"){ 
         alert("yes"); 
        } 
       } 

      }); 

      return false; //if i take this line out it submits either way 

     }); 

    }); 

我知道PHP的工作,因爲當一個用戶名採取或不正確的警告彈出,但我不能把它提交表單時的響應是YES,而不當的反應也沒將其提交。我在IF語句中嘗試過很多不同的東西(包括$(form).submit()和各種返回等),但無濟於事。

基本上,我需要它來當名字不採取提交,當它是...任何幫助是極大的讚賞,以不提交! (我認爲香港專業教育學院包括必要的潛在修復哈哈所有信息)

艾倫

+0

的可能重複[.submit)()無法正常工作,解除綁定(幫助,但配備了側面影響:P(http://stackoverflow.com/questions/8688532/submit-not-working-correctly-unbind -helps-but-with-a-side-affect-p) – 2011-12-31 16:32:40

回答

0

你試過(看註釋):

$(".form").submit(function(e) 
    { 
     var username = $(".userID").val(); 
     //cache the current form 
     var form = this; 
     //check if the event is started by the user or by your success function 
     //if it's triggered by the user, check for the username 
     if (e.originalEvent !== undefined){ 
      $.ajax({ 
      type: "POST", 
      url: "id_check.php", 
      data: "userID="+ username, 
      success: function(response){ 

       if(response=="NO"){ 
        alert("no");  
       } 
       else if(response=="YES"){ 
        //submit the form you have cached 
        $(form).submit(); 
        alert("yes"); 
       } 
      } 

      }); 

     //This is to prevent the form from submitting when you click the submit button 
     return false; //if i take this line out it submits either way 
     } 


    }); 
+0

感謝您的迴應。我想你修改什麼,它把它變成一個循環 - 警報「是」不停地彈出被點擊提交按鈕... – 2011-12-30 16:39:43

+0

@AlanWareham是的,當然,因爲它重新觸發形式,我修改了我的答案,以考慮該,基本上你檢查是否由用戶或呼叫 – 2011-12-30 16:50:30

+0

此停止從循環又一遍地打電話的形式產生的事件,和正確的信息仍顯示,但形式並不在任何情況下依然提交。 – 2011-12-31 12:17:18

0

返回false將不會允許按鈕提交這也是因爲返回false語句在ajax完成它的調用之前運行。所以我認爲你需要有一個隱藏的按鈕,當你的響應==「YES」時,你會調用它。

+0

所以一個隱藏的按鈕提交相同的形式,但只有當你的回答是肯定的時候纔會調用? – 2011-12-30 16:42:08

+0

是的......我之前試過,它運行良好。 – 2011-12-30 16:43:47

+0

也是$(「。form」)將是一個正常的輸入類型按鈕,它的點擊將決定您是否觸發提交按鈕。 – 2011-12-30 16:44:59