使用Ajax检查表单

时间:2013-01-10 17:18:54

标签: jquery ajax forms

我制作了一个小的jQuery Ajax代码来检查数据库中是否已存在电子邮件,我无法正常工作 我的Html代码:

<form name="emailForm" id="emailForm" method="post" action="signin.php">
    <input type="email" name="email" id="email" required="required" />
    <input type="submit" value="Get Started Now!" />
</form>

jQuery代码:

$(function(){
    $("#emailForm").submit(function(){
        $.ajax({
            type:POST,
            url:"signin.php",
            data: "email="+$("#email").val(),//{email:$("#email").val()},
            success: function(msg){
                if(msg == '1'){
                    alert("Already exists.");
                }else{
                    alert("C'est cool, Hak la suite");
                }
            }

        });
        return false;
    });
});

signin.php代码

function check_email($email){
    include 'bdd.php';
    $query = "SELECT * FROM users WHERE email = '$email'";
    $resultat = mysqli_query($link,$query);
    $msg = mysqli_num_rows($resultat);
    return $msg;
}
if(isset($_POST['email'])){
    if(check_email($_POST['email']) == 1){
        $msg = "1";
    }else{
        $msg = "0";
    }
}
echo $msg;

它转到signin.php并打印1或0,任何想法如何使Ajax工作?

2 个答案:

答案 0 :(得分:0)

您是否尝试使用以下代码

$(function(){
    $("#emailForm").submit(function(){
        $.ajax({
            type:POST,
            url:"signin.php",
            data: {"email":$("#email").val()},
            success: function(msg){
                if(msg == '1'){
                    alert("Already exists.");
                }else{
                    alert("C'est cool, Hak la suite");
                }
            }

        });
        return false;
    });
});

答案 1 :(得分:0)

试试这个,看看这是否有帮助:

 $(function () {
  $("#emailForm").submit(function (e) {
    $.ajax({
      type: 'POST', // in quotes
      url: "signin.php",
      data: {data:$(this).serialize()}, // serialize the form
      success: function (msg) {
        if (msg == '1') {
          alert("Already exists.");
        } else {
          alert("C'est cool, Hak la suite");
        }
      }
    });
    e.preventDefault();
  });
});