Registration Form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Pazuzu156
Forum Contributor
Posts: 241
Joined: Sat Nov 20, 2010 9:00 pm
Location: GA, USA
Contact:

Registration Form

Post by Pazuzu156 »

I have this registration form. When users register they are added to a roll on the members.php page that displays who they are and their user info. Though I can register and it works 100%, how would i make it where it will check if the username has already been used, and the registration page can tell them that the username is already in use?
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Registration Form

Post by Celauran »

Grab the value of the registration form's username field onkeyup. Use an XMLHttpRequest to pass the info to a PHP page that queries the database and returns whether or not that username exists, then display the responseText.

Code: Select all

<form id="frmAddUser" action="" method="post">
    ...
    <label for="username">Username:</label>
    <input type="text" name="username" onkeyup="checkUsernameAvailability();"/>
    <span id="usernameAvailable"></span><br />
    ...
</form>

Code: Select all

function checkUsernameAvailability()
{
    var username = document.getElementById('frmAddUser').username.value;

    xhr_username = new XMLHttpRequest();

    xhr_username.open('GET', 'foo.php?username=' + username, true);
    xhr_username.onreadystatechange = displayUsernameAvailability;
    xhr_username.send();
}

function displayUsernameAvailability()
{
    if (xhr_username.readyState == 4 && xhr_username.status == 200)
    {
        document.getElementById('usernameAvailable').innerHTML = xhr_username.responseText;
    }
}
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: Registration Form

Post by oscardog »

Just an FYI, Celauran, your AJAX won't work in any Internet Explorer. This was taken straight from Tizag and should work in all browsers:

Code: Select all

try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
To make it even easier, you should use jQuery as it does all of the legwork for you.
Post Reply