简体   繁体   中英

Live email availability check

I am trying to make live email availability check using ajax. I want to take the input value and send it to the php where it will be checked if it is in the database but I cannot make it. When I test the scripts with Firebug, there is a response but the output is always the same whatever the email is existing or not. It always shows me that is not existing.

The table is called company. The table field for emails is Email.

The connection to the database is OK. I think the problem is in my ajax code because it is always giving me "TAKEN" output.

This is my php code:

<?php
// This is a sample code in case you wish to check the username from a mysql db table

if(isset($_POST['Email']))
{
$email = $_POST['Email'];

$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = 'password';
$dbDatabase = 'php_test';

$db = mysql_connect($dbHost, $dbUsername, $dbPassword)
 or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db)
 or die ("Could not select database.");

$result = mysql_query("select Email from company where Email='".$email."'")
 or die(mysql_error());

if(mysql_num_rows($result))
{
echo 'NOT OK';
}
else
{
echo 'OK';
}
}
?>

This is the ajax code

$(document).ready(function() {

$("#email").blur(function(){
    $.ajax({  
    type: "POST",  
    url: "unique_check.php",  
    data: {Email: $("#email").val()},
    dataType:"json", 
    success: function(msg){

        if(msg == "OK"){
            alert("FREE")
        }else{
            alert("TAKEN")
        }
    }
    });
});    
}); 

Please, tell me where is my mistake or if there is a better way, give it. Keep in mind that I am new at ajax and php. Thank you very much!

I think you want:

if($result != false && mysql_num_rows($result) > 0) {
echo 'NOT OK';
} else {
echo 'OK';
}

If that doesn't work, try echoing out your query to make sure it is what you want.

One issue is that in your Javascript code, you're setting email at page load, which happens to be empty. You need to set email again inside your .blur() function to grab the value when the field actually blurs.

$(document).ready(function() {

    $("#email").blur(function(){
    var email = $("#email").val();
        $.ajax({  
            type: "POST",  
            url: "unique_check.php",  
            data: {Email: email},
            dataType:"json", 
            success: function(msg){

                if(msg == "OK"){
                    alert("FREE")
                }else{
                    alert("TAKEN")
                }
            }
        });
    });    
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM