Sui Go
Sui Go

Reputation: 463

Got problems on server side validation using PHP and AJAX

I just want to whenever after I type the email it will automatically display whether email can be used(not existed in db) or not(existed on db). When I type there is no output that displays.As of now I have this code. How should i fix this

Here's my main page code's

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Jquery-ajax Practice</title>
</head>

<body>
<section>
    <form>
        <label for="text_email">E-mail:</label>
        <input id="text_email" type="email" >

        <script type="text/javascript" charset="utf-8" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js">
            $(document).ready(function(){
                $('#text_email').keyup(function(){
                    email($(this).val());
                });
            });
            function email(str){
                $.post('checkmail.php',{ email: str},
                function(data){
                    $('#check_email').html(data.returnValue);
                }, 'json');
            }
        </script>

        <label for="text_email" id="check_email"></label>   
    </form>
</section>
</body>
</html>

Here's my php code

<?php
if(isset($_POST['email']))
{
    try 
    {
        $pdo=new PDO('mysql:host=localhost;dbname=class;charset=utf-8', 'root');
    }
    catch(PDOException $e)
    {
        echo 'Failed: '.$e->getMessage();
    }

    $stmt=$pdo->prepare('SELECT email FROM class where email=:email LIMIT 1');
    $stmt->execute(array(':email'=>$_POST['email']));
    if($stmt->rowCount()>0)
    {
        $check='E-mail cannot be use.';
    }
    else
    {
        $check='E-mail can be use.';
    }

    echo json_encode(array('returnValue'=>$check));
}
?>

Upvotes: 0

Views: 335

Answers (1)

jeroen
jeroen

Reputation: 91742

One problem I can see, is your handling of the database errors.

You should wrap all PDO operations in a try - catch block (not just the connection part) and when you catch an error, you would need to wrap that in your json_encode statement at the end as well and not just echo it out as that would invalidate the received json at the client side.

I don't know your database setup, but you are not providing a password and I think your connection string should have charset=utf8.

Upvotes: 1

Related Questions