Created
February 7, 2012 20:05
-
-
Save jvanasco/1761626 to your computer and use it in GitHub Desktop.
jquery username availability check - with timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Choose a username. You can't post until you do! | |
<form method="post" action="/account/choose-username"> | |
<input type="text" name="username" value="" id="username_selector"/> | |
<span id="fieldstatus-username"></span> | |
</form> | |
<script> | |
// on all keyups, set a message that the username is bad or that you're checking | |
// however, don't actually check until you have a timeout - e.g. .6 seconds | |
// there's no point on taxing a server to repeatedly check | |
var username_check_timer; | |
$( "#username_selector" ).keyup(function(event){ | |
window.clearTimeout( username_check_timer ); | |
var name= $("#username_selector").val(); | |
console.log(name); | |
var node= $("#fieldstatus-username"); | |
node.empty(); | |
if ( name.length < 5 ) { | |
node.append('<span class="fieldstatus--bad">Usernames must have at least 5 characters</span>'); | |
} | |
else { | |
node.append('<span class="fieldstatus--checking">checking…</span>'); | |
username_check_timer= window.setTimeout( username_check_ajax , 600 ); | |
} | |
}); | |
// actually handle the username check | |
// i like to use dicts/json objects to return data , so I can debug on the client site easier | |
// { status : 'success' , 'username_available' : true } | |
// { status : 'success' , 'username_available' : false } | |
// { status : 'error' , 'reason' : 'backend is having issues' } | |
function username_check_ajax(){ | |
$.ajax({\ | |
url: '/api/internal/username-availability', | |
data: { username : name }, | |
success: function( data, textStatus, jqXHR ) { | |
var node= $("#fieldstatus-username"); | |
node.empty(); | |
if ( textStatus == 'success' ) { | |
if ( data['username_available'] == true ) { | |
node.append('<span class="fieldstatus--good">Available!</span>'); | |
} | |
else { | |
node.append('<span class="fieldstatus--bad">Not Available!</span>'); | |
} | |
} else { | |
node.append('<span class="fieldstatus--bad">Error (this might be bad)</span>'); | |
} | |
} | |
}); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment