Simple login form Notice: Undefined index: username

Howdy! I’m at a loss after looking at this for almost an hour. I need another pair of eyes or another brain for that matter. This is a simple form to pass parameters to an ajax script to check availability of the user name. I’m getting this

Notice: Undefined index: username

and I can’t figure it out. If someone could point out what I’m overlooking I’d appreciate it.
Here’s the PHP

<?php
//get the username
$username = mysql_real_escape_string($_POST['username']);

//mysql query to select field username if it's equal to the username that we check '
$result = mysql_query('SELECT user_name FROM ajax_users WHERE user_name = "'. $username .'"');
echo $username;//for testing
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysql_num_rows($result)>0){
	//and we send 0 to the ajax request
	echo 0;
}else{
	//else if it's not bigger then 0, then it's available '
	//and we send 1 to the ajax request
	echo 1;
}
?>

Here is the form:

<fieldset>

        <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="signup">

            <ul class="form">
                <li><label for="user_name">Username</label></li>
                <li><input type='text' id='username'></li>
                <li><input type='button' id='check_username_availability' value='Check Availability'></li>
                <span id='username_availability_result'></span>
            </ul>

        </form>

    </fieldset>

I appreciate it

When you submit a form, what is sent back to the server are the names and values from the form elements. Your inputs have no names. The id attribute is only used for CSS selectors and JavaScript.

$_POST[‘username’] is therefore not set, generating the notice.

Is is good coding practice to use @ to suppress the Notice, like this.

$username = @mysql_real_escape_string($_POST['user_name']);

Suppressing the notice is not good coding practice, no.

Good coding practice would be to check if $_POST[‘user_name’] is set before using it.

if (!isset($_POST['user_name'])) {
  echo "Uhoh, you need to fill out the whole form!";
  exit;
}

And, at minimum, check that it’s not an empty string before allowing it as a username.

if (empty($_POST['user_name'])) {
  echo "Uhoh, you need to fill out the whole form!";
  exit;
}

Though you’d want to handle the error more gracefully than simply printing a message and exiting.

Thanks. That was the answer I was looking for. You don’t know how many times I’ve been told that it doesn’t matter as long as the user doesn’t see it. And you don’t know how many tutorials I’ve spent hours on that produce these types of errors, notices and warnings. I don’t understand those that write tutorials and either don’t use good coding practices or publish the tutorial without testing their own source. It’s getting so frustrating trying to learn.

Thanks again