检查是否存在使用ajax的电子邮件


Check if email exist using ajax

基本上,我想检查电子邮件是否自动存在于数据库中。当connection.php &插入mysqli查询

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);

您在ajax调用函数的成功块中,在if条件下获得响应时犯了一个小错误。

在if条件

中将date重写为data
$( 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
            }
        });
    });
});

当您使用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);

我想你忘记在Ajax中添加请求方法:type:'post'当然,在PHP中修复:将GET更改为POST