Jump to content

Username availability button


chao

Recommended Posts

I'm making a registration form with a username field. I'd like an AJAX button to check if an entered username is available. The usernames are stored in a MySQL database.

 

Here's an example of such a button: http://www.youtube.com/signup?next=/index

 

I found some code online, but it's excessive and difficult to read. I'd like to make a simple one myself. Do you have any guides or recommendations? Thanks.

Link to comment
https://forums.phpfreaks.com/topic/134546-username-availability-button/
Share on other sites

this needs two parts...first is a server side script (probably PHP) that receives the username and returns if it is available or not. here is an example:

 

<?php
  $user = $_GET['user'];
  $sql = sprintf("SELECT COUNT(*) FROM `users` WHERE `username` = '%s'",mysql_real_escape_string($user));
  list($test) = mysql_fetch_array(mysql_query($sql));
  print $test ? 1 : 0;
?>

 

Then, for the Ajax, just call that script with the value of the username as a GET variable. do you need help with that part too?

 

the second part is the ajax that calls the script.

Using jQuery, the AJAX would look like:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
  function check_username ( ) {
    document.getElementById('user_status').innerHTML = '';
    $.get("check_user.php", { user: document.getElementById('username').value },
      function(data){
        document.getElementById('user_status').innerHTML = parseInt(data)
          ? 'Username Available'
          : 'Username Not Available';
      }
    );
  }
</script>
<input type="text" id="username" name="username" />
<input type="button" value="Check Availability" onclick="check_username()" />
<span id="user_status"></span>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.