Friday, 22 July 2011

Get data from DB without refreshing, Login

The html,
  <div id="wrapper">
    <form name="form">
        Username: <input class="input" type="text" name="name" id="text"/><br>
        Password: <input class="input" type="password" name="password" id="password"/><br>
        <input type="button" name="button" id="button" value="Check"/>
    </form>
    <div id="box"></div>
    </div>

The jQuery,
  $(function(){
         $('#button').click(function(){
             $.ajax({
                 url:'data.php',
                 type:'post',
                 data:'name='+$("#text").val()+'&password='+$("#password").val(),
                 success:function(result){
                           $('#box').html(result);
                            }
         });
  });
  });

The CSS
<style type="text/css">
    body
    {
        background-color: azure;
    }
    #box
    {
        color: green;
        position: relative;
        top:15px;
        
    }
    .input
    {
        background: lemonchiffon;
    }
    #button
    {
       position: relative;
       top:10px;
    }
    #wrapper
    {
        position:relative;
        left:500px;
        top:200px;
        border:2px solid black;
        padding:50px;
        width:200px;
        background-color:  white;
    }
</style>

data.php file,
<?php
$name=$_POST['name'];
$password=$_POST['password'];
if(empty($name)){
    echo "Please enter a username";
}

else
{
$conn= new mysqli('localhost','root','','user') or die("Could not connect to the DB");
$sql = 'SELECT password FROM user WHERE username=?';
$stmt=$conn->prepare($sql) or die("problem with query");
$stmt->bind_param('s',$name) or die("could not bind");
$stmt->execute();
$stmt->bind_result($pass);
$stmt->fetch();
if($pass)
{
    if($pass==$password)
      echo "Correct!";
    else
        echo "Sorry, the password is wrong";
        
}else
    echo "You have entered an invalid username";

$conn->close();
}

?>

It is not a good idea to take the input from the user as such, a mysql_real_escape_string on the input
will provide some kind of security.




No comments:

Post a Comment