2016-09-22 137 views
0

基本上,我想檢查電子郵件是否自動存在於數據庫中。當插入查詢connection.php & mysqli時,該功能將不起作用。使用ajax檢查電子郵件是否存在

HTML:

<input type="email" name="email" class="formEmail"> 

JS:

$(document).ready(function() { 
    $('.formEmail').on('change', function() { 
     //ajax request 
     $.ajax({ 
      url: "queries/checkEmail.php", 
      data: { 
       'email' : $('.formEmail').val() 
      }, 
      dataType: 'json', 
      success: function(data) { 
       if(date == true) { 
        alert('Email exists!'); 
       } 
       else { 
        alert('Email doesnt!'); 
       } 
      }, 
      error: function(data){ 
       //error 
      } 
     }); 
    }); 
    }); 

PHP:

require_once("../connection.php"); 

$userEmail = $_GET['email']; 

$checkEmail=mysqli_query($con, "SELECT email from accounts WHERE email='$userEmail'"); 

if (mysqli_num_rows($checkEmail) == 1) { 
    $response = true; 
} else { 
    $response = false; 
} 

echo json_encode($response); 
+5

'數據== date' – Andreas

+1

你很容易受到[SQL注入攻擊(http://bobby-tables.com) –

+0

@Andreas感謝您的幫助!我將日期更改爲數據,但仍然無法正常工作。 –

回答

1

您獲得重新犯了個小錯誤在調用函數ajax的成功塊中調用if條件。

重寫datedata中,如果條件

$(document).ready(function() { 
    $('.formEmail').on('change', function() { 
     //ajax request 
     $.ajax({ 
      url: "queries/checkEmail.php", 
      data: { 
       'email' : $('.formEmail').val() 
      }, 
      dataType: 'json', 
      success: function(data) { 
       if(data == true) { 
        alert('Email exists!'); 
       } 
       else { 
        alert('Email doesnt!'); 
       } 
      }, 
      error: function(data){ 
       //error 
      } 
     }); 
    }); 
}); 
+0

您還可以使用'keyup()'功能動態檢查命中服務器並檢查電子郵件 – Kathirmalan

+0

感謝您的幫助。我將日期更改爲數據,但仍然無法正常工作。 –

+0

在這裏發佈你的「錯誤信息」,我會幫你解決這個問題。你可能想在你的AJAX調用函數之前調用JQuery腳本。 – Kathirmalan

0

當您使用Ajax和你的輸出是JSON,你需要發送純JSON只輸出,請檢查下面的代碼。我已經加入checkEmail.php文件中的JSON消息的頭,所以它可以由JavaScript

代碼

<?php 
require_once("../connection.php"); 

$userEmail = $_GET['email']; 

$checkEmail=mysqli_query($con, "SELECT email from accounts WHERE email='$userEmail'"); 

if (mysqli_num_rows($checkEmail) == 1) { 
    $response = true; 
} else { 
    $response = false; 
} 

//Here your required to set the header which will make output as pure JSON output and easy to read by javascript 

header('Content-Type:application/json;'); 
echo json_encode($response); 
+0

你測試過了嗎?還是行不通 :( –

0

我想你忘了在阿賈克斯添加請求方法輕鬆讀取:type:'post' 而在PHP當然修復:改變GETPOST

相關問題