2016-09-22 52 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