Welcome Guest [Log In] [Register]
Add Reply
Nice AJAX Username Availability
Topic Started: Sep 6 2008, 11:51 PM (154 Views)
JakkyD
Member Avatar

Nice little extra to add to register.php. You enter a username in and it will say whether its available or not :)




ajax.php

Code:
 

<?php
include ("include/constants.php");
mysql_connect (DB_SERVER, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);

$do = $_GET['do'];
switch($do) {
case 'check_username_exists':
if(get_magic_quotes_gpc()) {
$username = $_GET['username'];
}else{
$username = addslashes($_GET['username']);
}
$count = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `username`='".$username."'"));
header('Content-Type: text/xml');
header('Pragma: no-cache');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<result>';
if($count > 0) {
echo 'That username already exists, please select another one.';
}else{
echo 'That username is available.';
}
echo '</result>';
break;
default:
echo 'Error, invalid action';
break;
}
?>


usernamecheck.php

Code:
 

<script type="text/javascript">
function toggle_username(userid) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
handle = document.getElementById(userid);
var url = 'ajax.php?';
if(handle.value.length > 0) {
var fullurl = url + 'do=check_username_exists&username=' + encodeURIComponent(handle.value);
http.open("GET", fullurl, true);
http.send(null);
http.onreadystatechange = statechange_username;
}else{
document.getElementById('username_exists').innerHTML = '';
}
}

function statechange_username() {
if (http.readyState == 4) {
var xmlObj = http.responseXML;
var html = xmlObj.getElementsByTagName('result').item(0).firstChild.data;
document.getElementById('username_exists').innerHTML = html;
}
}
</script>
<div>
<input id="username" type="text" name="username" onchange="toggle_username('username')" style="float:left" />
<div id="username_exists" style="font-size:14px; font-family:Arial, Helvetica, sans-serif; font-weight: bold; color:#FF3300; float:left; margin-left:10px; margin-top:4px"></div>
</div>





Note I had these on seperate files. So change it to your liking. :)

Offline Profile Quote Post Goto Top
 
feartec

i will add this script to the beta version
Offline Profile Quote Post Goto Top
 
JakkyD
Member Avatar

Cool, remember to change var url = 'ajax.php?'; ;)
Offline Profile Quote Post Goto Top
 
feartec

yes i did, but it's not working

You forgot to say that everybody has to add id="username" at the username input tag.
Edited by feartec, Sep 7 2008, 01:19 PM.
Offline Profile Quote Post Goto Top
 
1 user reading this topic (1 Guest and 0 Anonymous)
« Previous Topic · Other · Next Topic »
Add Reply