Utilizando la función.docx
- 1. Utilizando la función $.ajax(), el código debería ser similar a:
$.ajax({
type : 'POST',
url : 'username-check.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
}
});
Utilizando la función $.post(), el código debería ser similar a:
$.post("username-check.php", $("#reg-form").serialize())
.done(function(data){
$("#result").html(data);
});
Index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Live Username Availability Check using PHP PDO and jQuery</title>
<script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#name").keyup(function()
{
var name = $(this).val();
if(name.length > 3)
{
$("#result").html('checking...');
/*$.post("username-check.php", $("#reg-form").serialize())
.done(function(data){
$("#result").html(data);
});*/
$.ajax({
type : 'POST',
url : 'username-check.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
}
});
return false;
- 2. }
else
{
$("#result").html('');
}
});
});
</script>
</head>
<body>
<form id="reg-form" action="" method="post" autocomplete="off">
<fieldset>
<div>
<input type="text" name="name" id="name" placeholder="Username" />
<span id="result"></span>
</div>
</fieldset>
</form>
</body>
</html>
Username-check.php
<?php
$host="localhost";
$user="root";
$pass="";
$dbname="dbtest";
$dbcon = new PDO("mysql:host={$host};dbname={$dbname}",$user,$pass);
if($_POST)
{
$name = strip_tags($_POST['name']);
$stmt=$dbcon->prepare("SELECT user_name FROM users WHERE user_name=:name");
$stmt->execute(array(':name'=>$name));
$count=$stmt->rowCount();
if($count>0)
{
echo "<span style='color:brown;'>Sorry username already taken !!!</span>";
}
else
{
- 3. echo "<span style='color:green;'>available</span>";
}
}
?>
Style.css
@charset "utf-8";
/* CSS Document */
*{margin:0; padding:0;}
#reg-form
{
margin:100px auto;
padding:25px;
border:solid #cfcfcf 1px;
width:50%;
background:#f9f9f9;
}
fieldset
{
padding:5px;
width:60%;
margin:0 auto;
border:0;
}
input
{
width:100%;
height:35px;
border:solid #00a2d1 1px;
padding-left:10px;
font-family:Verdana, Geneva, sans-serif;
font-weight:bold;
font-size:15px;
}
span
{
font-family:Verdana, Geneva, sans-serif;
font-weight:bold;
font-size:15px;
}