2016-01-25 61 views
1

我有一個註冊頁面,我使用jquery validation驗證所有字段條目。我如何使用jquery驗證我的表單以檢查mysql數據庫中的重複項?我試圖使用遠程方法,但是當我輸入已經在數據庫中的電子郵件時,沒有任何反應。使用jQuery驗證插件查找重複電子郵件

sign_up.php

$("#feedbackForm").validate({ 
    rules: { 
     email: { 
      required: true, 
      email: true, 
      remote: "inc/check_email.php" 
     } 
    }, 
    messages: { 
     email: { 
      email: "Insert valid adress", 
      required: "Please complete email field", 
      remote: "Email is already in use, please change it." 
     } 
    } 
}); 

/inc/check_email.php

<?php 

include('config.php'); 

$email = $_POST['email']; 
$query = mysql_query("SELECT * FROM table WHERE email = '" . $email . "'"); 

if (mysql_num_rows($query) > 0) { 
    return true; 
} else{ 
    return false; 
} 
+0

也許插件期待JSON。 true/false不能通過axaj調用正確返回 –

+0

在jQuery中使用$ .validator.addMethod – msvairam

+0

您必須返回「true」或「false」而不是true或false。回報必須像Robert說的那樣以json格式。 – lwb

回答

1

documentation來自:

服務器側響應必須是JSON字符串必須對於有效的元素是「真實的」 ,並且對於無效元素,可以使用默認錯誤消息爲「false」,未定義或爲null。如果服務器端響應是一個字符串,例如。 「該名稱已被使用,請嘗試使用peter123」,則此字符串將顯示爲自定義錯誤消息以代替默認值。

所以,你需要改變你如果到:

$array = ['email' => 'true']; 
if (mysql_num_rows($query) > 0) { 
    $array['email'] = 'Email is duplicated'; 
} 

echo json_encode($array); 

此外,你應該改變你的數據庫引擎PDO或mysqli的。 Mysql_ *函數已被棄用。

0

看到這個網址

http://jqueryvalidation.org/files/demo/ajaxSubmit-integration-demo.html

jQuery(function() { 
     $.mockjax({ 
      url: "login.action", 
      response: function(settings) { 
       var user = settings.data.match(/user=(.+?)($|&)/)[1], 
        password = settings.data.match(/password=(.+?)($|&)/)[1]; 
       if (password !== "foobar") { 
        this.responseText = "Your password is wrong (must be foobar)."; 
        return; 
       } 
       this.responseText = "Hi " + user + ", welcome back."; 
      }, 
      responseStatus: 200, 
      responseTime: 500 
     }); 

     // show a simple loading indicator 
     var loader = jQuery('<div id="loader"><img src="images/loading.gif" alt="loading..."></div>') 
      .css({ 
       position: "relative", 
       top: "1em", 
       left: "25em", 
       display: "inline" 
      }) 
      .appendTo("body") 
      .hide(); 
     jQuery().ajaxStart(function() { 
      loader.show(); 
     }).ajaxStop(function() { 
      loader.hide(); 
     }).ajaxError(function(a, b, e) { 
      throw e; 
     }); 

     var v = jQuery("#form").validate({ 
      submitHandler: function(form) { 
       jQuery(form).ajaxSubmit({ 
        target: "#result" 
       }); 
      } 
     }); 

     jQuery("#reset").click(function() { 
      v.resetForm(); 
     }); 
    }); 
0

插件期待一個JSON,感謝大家。

if (mysql_num_rows($query) > 0) { 
echo json_encode(FALSE); 
} else{ 
echo json_encode(TRUE); 
}