Hi all,

I am setting up a registration form for a website im building.
When the user enters his/her information i would like to validate that the Username/Email aren't already in use.
At this point in time ive got my mind set on a function that runs 2 seconds after anything is typed into the Textbox.
This function works, it returns "Available" or "In use" when it should.
The problem is;
when the user begins to type, i would like my image (ajax-loader.gif) to appear, and when the script gives a result, i want the image to hide again.
but this only works ONCE.

My Code:
jQuery:

<script type="text/javascript">
$(document).ready(function() {
    $("#username").keyup(function(){
        $("#loading").show();
        setTimeout(function(){
            var entered_text = $("#username").val();
            validateUsername(entered_text);
            $("#loading").hide();
        }, 2000);
    });
});
function validateUsername(username)
{
    $("#username_valid").load("validate_username.php?Username=" + username);

}
</script>

HTML:

<tr><td>Username:</td><td colspan="2"><input id="username" type="text" name="username" /></td><td id="username_valid"><img id="loading" style="display:none;" src="ajax-loader.gif"/></td></tr>

(This is the only line of my HTML code that is relevant to my issue.)

PHP/MySQL:

<?php
$username = $_REQUEST['Username'];
$con = mysql_connect('*******', '******', '*******');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db('users', $con);
$sql_query = mysql_query("SELECT 'username' FROM `users` WHERE `username`='" . $username . "'");
if(mysql_num_rows($sql_query)==1)
{
    echo "Sorry this name is already taken!";
}
else
{
    echo "This name is available!";
}

?>

I really stuck on this one.
Any help is appreciated.

Cheers, James

Dani AI

Generated

Short answer: the loading image is being removed by your .load() call. In your HTML the <img id="loading"> is inside #username_valid, and $("#username_valid").load(...) replaces that element's contents — so the loader exists only the first time. Also, calling setTimeout on every keyup without cancelling previous timers will create multiple requests. was right to flag sanitization as well.

Move the loader outside the element you replace and debounce the input so you only send one request after the user pauses. Example layout and client-side pattern (keeps the loader separate, uses input event, clears previous timer, and hides loader in the AJAX completion handler):

<input id="username" name="username" />
<img id="loading" src="ajax-loader.gif" style="display:none" />
<span id="username_valid"></span>
var timer = null;
$('#username').on('input', function() {
  var $me = $(this);
  clearTimeout(timer);
  timer = setTimeout(function() {
    var name = $me.val().trim();
    if (!name) { $('#username_valid').text(''); $('#loading').hide(); return; }
    $('#loading').show();
    $.get('validate_username.php', { Username: name })
      .done(function(resp){ $('#username_valid').html(resp); })
      .fail(function(){ $('#username_valid').text('Error'); })
      .always(function(){ $('#loading').hide(); });
  }, 600); // debounce delay
});

Server-side: stop using mysql_*. Use prepared statements (PDO or mysqli) and a lightweight query such as SELECT 1 FROM users WHERE username = ? LIMIT 1. Example PDO pattern:

$db = new PDO(..., [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $db->prepare('SELECT 1 FROM users WHERE username = ? LIMIT 1');
$stmt->execute([$username]);
$exists = (bool)$stmt->fetchColumn();

Extra tips: check the browser console for JS errors (as asked), ensure the loader path is correct, use server-side uniqueness (unique index) to enforce correctness, and always validate/sanitize inputs on the server.

Recommended Answers

All 3 Replies

Member Avatar for Member #905211

are there any JavaScript errors?

Member Avatar for Member #905211

Also what is stopping me from entering the username as ' go drop table users -- or any other query that can complete screw up your database? You might want to think about sanitizing input or using stored procedures.

You might want to think about sanitizing input or using stored procedures.

Thanks, i actually did NOT think of this.
Im going to rethink my strategy for validating the form.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.