使用jQuery和PHP检查数据库中是否已存在电子邮件地址

时间:2012-07-26 06:46:46

标签: php jquery mysql

我正在尝试验证电子邮件地址(如果它已存在于表格中),但这不起作用。

这是我的代码:

<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$('#Submit').click(function() {
    var emailVal = $('#email').val(); // assuming this is a input text field
    $.post('checkemail.php', {'email' : emailVal}, function(data) {
        alert(data);
    });
});
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="view.php">
  <p>
    <input type="text" name="email" id="email" />
  </p>
  <p>
     <input type="submit" name="Submit" id="Submit" value="Submit" />
  </p>
</form>
</body></html>

单击“提交”按钮时,应首先使用jQuery进行验证并调用checkemail.php文件,如下所示:

<?php
include("../includes/db.php");

$sql = "SELECT email FROM lf_clients WHERE email = " .$_POST['email'];
$select = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($select);

if (mysqli_num_rows > 0) {
    echo "The email already exists.";
}
?>

然而,当我点击提交按钮时,它会转到view.php而不是checkemail.php。在重定向到view.php之前,它应首先检查电子邮件是否已存在。如果电子邮件已存在,则不应重定向到view.php。

5 个答案:

答案 0 :(得分:11)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //newly added 
$('#Submit').click(function() {alert('in');
    var emailVal = $('#email').val(); // assuming this is a input text field
    $.post('checkemail.php', {'email' : emailVal}, function(data) {
        if(data=='exist') return false;
        else $('#form1').submit();
    });
});});
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="view.php">
  <p>
    <input type="text" name="email" id="email" />
  </p>
  <p>
    <input type="button" name="Submit" id="Submit" value="Submit" />
  </p>
</form>
</body>
</html>

php Code

<?php
include("../includes/db.php");

$sql = "SELECT email FROM lf_clients WHERE email = " .$_POST['email'];
$select = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($select);

if (mysqli_num_rows > 0) {
    echo "exist";
}else echo 'notexist';
?>

答案 1 :(得分:1)

这类东西的最佳实践是使用Jquery远程验证方法。

  $("#myform").validate({
      rules: {
        email: {
          required: true,
          email: true,
          remote: "check-email.php"
        }
      },
      messages:{
         email:'Email address exists.'
     }
    });

在PHP文件中,您可以执行@Sachyn所提到的内容。

答案 2 :(得分:0)

我怀疑您必须中止提交按钮的标准操作。您也可能需要将操作从单击更改为提交,但现在无法对其进行测试。

$('#Submit').submit(function(e) {
    var usernameVal = $('#email').val(); // assuming this is a input text field
    $.post('checkemail.php', {'email' : emailVal}, function(data) {
        alert('data');
    });
    e.preventDefault(); // <------
});

答案 3 :(得分:0)

您可以执行以下操作

  1. 在您的PHP文件中 -

     if (mysqli_num_rows > 0) {
          echo "0"; // email exists
     else
          echo "1"; // email doesn't exists
     return;
    
  2. 在您的HTML文件中,使用<input type="button"代替<input type="submit"

  3. 在JavaScript中

    $.post('checkemail.php', {'email' : emailVal}, function(data) {
       if (data == 1)
       { 
           $("#form1").submit();
       }
       else
       {
            alert("Email already exists");
            return false;
       }
    });
    

答案 4 :(得分:0)

如果您更喜欢使用 JQuery 进行检查,可以按如下方式进行

$('document').ready(function(){
 var username_state = false;
 var email_state = false;
 $('#username').on('blur', function(){
  var username = $('#username').val();
  if (username == '') {
    username_state = false;
    return;
  }
  $.ajax({
    url: 'register.php',
    type: 'post',
    data: {
        'username_check' : 1,
        'username' : username,
    },
    success: function(response){
      if (response == 'taken' ) {
        username_state = false;
        $('#username').parent().removeClass();
        $('#username').parent().addClass("form_error");
        $('#username').siblings("span").text('Sorry... Username already taken');
      }else if (response == 'not_taken') {
        username_state = true;
        $('#username').parent().removeClass();
        $('#username').parent().addClass("form_success");
        $('#username').siblings("span").text('Username available');
      }
    }
  });
 });        
  $('#email').on('blur', function(){
    var email = $('#email').val();
    if (email == '') {
        email_state = false;
        return;
    }
    $.ajax({
      url: 'register.php',
      type: 'post',
      data: {
        'email_check' : 1,
        'email' : email,
      },
      success: function(response){
        if (response == 'taken' ) {
          email_state = false;
          $('#email').parent().removeClass();
          $('#email').parent().addClass("form_error");
          $('#email').siblings("span").text('Sorry... Email already taken');
        }else if (response == 'not_taken') {
          email_state = true;
          $('#email').parent().removeClass();
          $('#email').parent().addClass("form_success");
          $('#email').siblings("span").text('Email available');
        }
      }
    });
 });

 $('#reg_btn').on('click', function(){
    var username = $('#username').val();
    var email = $('#email').val();
    var password = $('#password').val();
    if (username_state == false || email_state == false) {
      $('#error_msg').text('Fix the errors in the form first');
    }else{
      // proceed with form submission
      $.ajax({
        url: 'register.php',
        type: 'post',
        data: {
            'save' : 1,
            'email' : email,
            'username' : username,
            'password' : password,
        },
        success: function(response){
            alert('user saved');
            $('#username').val('');
            $('#email').val('');
            $('#password').val('');
        }
      });
    }
 });
});
body {
  background: #A9D9C3;
}
#register_form h1 {
  text-align: center;
}
#register_form {
  width: 37%;
  margin: 100px auto;
  padding-bottom: 30px;
  border: 1px solid #918274;
  border-radius: 5px;
  background: white;
}
#register_form input {
  width: 80%;
  height: 35px;
  margin: 5px 10%;
  font-size: 1.1em;
  padding: 4px;
  font-size: .9em;
}
#reg_btn {
  height: 35px;
  width: 80%;
  margin: 5px 10%;
  color: white;
  background: #3B5998;
  border: none;
  border-radius: 5px;
}
/*Styling for errors on form*/
.form_error span {
  width: 80%;
  height: 35px;
  margin: 3px 10%;
  font-size: 1.1em;
  color: #D83D5A;
}
.form_error input {
  border: 1px solid #D83D5A;
}

/*Styling in case no errors on form*/
.form_success span {
  width: 80%;
  height: 35px;
  margin: 3px 10%;
  font-size: 1.1em;
  color: green;
}
.form_success input {
  border: 1px solid green;
}
#error_msg {
  color: red;
  text-align: center;
  margin: 10px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<html>
<head>
  <title>Register</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
 <form id="register_form">
      <h1>Register</h1>
      <div id="error_msg"></div>
      <div>
        <input type="text" name="username" placeholder="Username" id="username" >
        <span></span>
      </div>
      <div>
        <input type="email" name="email" placeholder="Email" id="email">
        <span></span>
      </div>
      <div>
       <input type="password" name="password" placeholder="Password" id="password">
      </div>
      <div>
        <button type="button" name="register" id="reg_btn">Register</button>
      </div>
    </form>
</body>
</html>
<!-- scripts -->
<script src="script.js"></script>

要使此代码完全发挥作用,它需要自己的后端。但是通过查看这段代码,您可以了解如何检查数据库中是否存在任何字段的基本流程。 这是执行主要工作的主要代码。

  $('#email').on('blur', function(){
var email = $('#email').val();
if (email == '') {
    email_state = false;
    return;
}
$.ajax({
  url: 'register.php',
  type: 'post',
  data: {
    'email_check' : 1,
    'email' : email,
  },
  success: function(response){
    if (response == 'taken' ) {
      email_state = false;
      $('#email').parent().removeClass();
      $('#email').parent().addClass("form_error");
      $('#email').siblings("span").text('Sorry... Email already taken');
    }else if (response == 'not_taken') {
      email_state = true;
      $('#email').parent().removeClass();
      $('#email').parent().addClass("form_success");
      $('#email').siblings("span").text('Email available');
    }
  }
});

});

您可以从 Source

获取后端