1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Check username

Discussion in 'PHP' started by oo7ml, Jul 8, 2007.

  1. #1
    Hi, I have a join form on my site. Beside the username field is a button called "check username". If a user clicks this button, a new small window opens in the center of the screen and it allows the user to type in a username to check if it is available.

    Is there a way that i can just click the button on the form, and instead of opening up a new small window, the button will just check the username that the user has typed into the username field on the form. This will save the user having to type the username into the new window again when it opens.

    Here is the code that the small window performs for checking the username
    
    $username = mysql_real_escape_string($_POST['username']);
    $check = mysql_query("SELECT username FROM accounts WHERE username = '$username'")
    or die(mysql_error());
    $check2 = mysql_num_rows($check);
    
    //if the name exists it gives an error
    if ($check2 != 0) {
    echo(sorry, username is in use);
    }
    else
    {
    echo(username is available);
    }
    PHP:
    Surely there is someway i can put this sort of code into my join.php (join form) page... i'm not sure how or if that is the best way to do it, please help... thanks in advance
     
    oo7ml, Jul 8, 2007 IP
  2. ansi

    ansi Well-Known Member

    Messages:
    1,483
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    100
    #2
    sure, take some kind of ajax approach to it.
     
    ansi, Jul 8, 2007 IP
  3. dankenpo

    dankenpo Guest

    Messages:
    30
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Here's an Ajax approach the aspx route:

    
    <%@ Page Language="C#"%>
    <%@ Import Namespace="System.Web.Services" %>
    <%@ Import Namespace="System.Web.Security" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <script runat="server">
        [WebMethod()]
        public static bool CheckUserName(string userName)
        {
            return (Membership.GetUser(userName) != null);
        }
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Create User</title>
        <script type="text/javascript">
    
        var _txtUserName;
        var _divStatus;
        var _timerHandle;
    
        function pageLoad()
        {
            _txtUserName = $get('<%= CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName").ClientID %>');
            _divStatus = $get('<%= CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("divStatus").ClientID %>');
            $addHandler(_txtUserName, "keyup", onKeyUp);
        }
    
        function pageUnload()
        {
            $removeHandler(_txtUserName, "keyup", onKeyUp);
            clearTimer();
        }
    
        function onKeyUp(e)
        {
            setupTimer();
        }
    
        function setupTimer()
        {
            clearTimer();
            _timerHandle = window.setTimeout(checkUserName, 500)
        }
    
        function clearTimer()
        {
            if (_timerHandle != null)
            {
                window.clearTimeout(_timerHandle);
                _timerHandle = null;
            }
        }
    
        function checkUserName()
        {
            if (_txtUserName.value.length > 2)
            {
                _divStatus.innerHTML = 'Checking...';
                _divStatus.style.color = 'black';
                PageMethods.CheckUserName(_txtUserName.value, OnCheckUserNameComplete, OnCheckUserNameError, _txtUserName.value);
            }
        }
        
        function OnCheckUserNameComplete(result, userContext)
        {
            if (result == true)
            {
                _divStatus.innerHTML = String.format('\'{0}\' is already taken', userContext);
                _divStatus.style.color = 'red';
            }
            else
            {
                _divStatus.innerHTML = String.format('\'{0}\' is available', userContext);
                _divStatus.style.color = 'green';
            }
        }
    
        function OnCheckUserNameError(e)
        {
            _divStatus.innerHTML = e.get_message();
            _divStatus.style.color = 'red';
        }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager  ID="theScriptManager" runat="server" EnablePageMethods="true">
                </asp:ScriptManager>
                <asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
                    <WizardSteps>
                        <asp:CreateUserWizardStep runat="server">
                            <ContentTemplate>
                                <table border="0">
                                    <tr>
                                        <td align="center" colspan="2">Sign Up for Your New Account</td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label></td>
                                        <td>
                                            <asp:TextBox ID="UserName" runat="server"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
                                            <div id="divStatus" runat="server"></div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label></td>
                                        <td>
                                            <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">Confirm Password:</asp:Label></td>
                                        <td>
                                            <asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="ConfirmPassword" ErrorMessage="Confirm Password is required." ToolTip="Confirm Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">E-mail:</asp:Label></td>
                                        <td>
                                            <asp:TextBox ID="Email" runat="server"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="Email" ErrorMessage="E-mail is required." ToolTip="E-mail is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <asp:Label ID="QuestionLabel" runat="server" AssociatedControlID="Question">Security Question:</asp:Label></td>
                                        <td>
                                            <asp:TextBox ID="Question" runat="server"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="QuestionRequired" runat="server" ControlToValidate="Question" ErrorMessage="Security question is required." ToolTip="Security question is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <asp:Label ID="AnswerLabel" runat="server" AssociatedControlID="Answer">Security Answer:</asp:Label></td>
                                        <td>
                                            <asp:TextBox ID="Answer" runat="server"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="AnswerRequired" runat="server" ControlToValidate="Answer" ErrorMessage="Security answer is required." ToolTip="Security answer is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="center" colspan="2">
                                            <asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" Display="Dynamic" ErrorMessage="The Password and Confirmation Password must match." ValidationGroup="CreateUserWizard1"></asp:CompareValidator>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="center" colspan="2" style="color: red">
                                            <asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>
                                        </td>
                                    </tr>
                                </table>
                            </ContentTemplate>
                            <CustomNavigationTemplate>
                                <table border="0" cellspacing="5" style="width: 100%; height: 100%;">
                                    <tr align="right">
                                        <td align="right" colspan="0">
                                            <asp:Button ID="StepNextButton" runat="server" CommandName="MoveNext" Text="Create User" ValidationGroup="CreateUserWizard1" />
                                        </td>
                                    </tr>
                                </table>
                            </CustomNavigationTemplate>
                        </asp:CreateUserWizardStep>
                        <asp:CompleteWizardStep runat="server">
                        </asp:CompleteWizardStep>
                    </WizardSteps>
                </asp:CreateUserWizard>
            </div>
        </form>
    </body>
    </html>
    
    PHP:
    The steps are very simple:

    1. Add a CreateUserWizard Control and then Convert the Steps to Custom Template.
    2. Add a Div Tag right beside the User Name textbox.
    3. Create a Static method which accepts UserName and checks the Membership Provider for the existence.
    4. In the ClientSide hook the keydown event of the User name text box.
    5. Create a Timer so that we do not have to invoke the Server Side method upon each key press.
    6. Call the Server side method to check the whether the user name is available.

    To see a single page example instead of creating Code behind file and Web service, go to http://geekswithblogs.net/rashid/archive/2007/06/30/Check-User-Name-in-Ajax-way.aspx
     
    dankenpo, Jul 8, 2007 IP
    ansi likes this.
  4. pfek

    pfek Member

    Messages:
    98
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    45
    #4
    Hi,

    you should trow an ajax command on the "onChange" event of your username input. This command would then lookup in your database if the username is already taken. Then, it would send back a response writing in a div something like "Username taken" or "Username free!". This would cause no reload and would act as you initialy planned.

    If you are using a library like xAjax, you would have to use the following lines

    For your input :
    onchange="xajax_ValidateUsername(document.getElementById('txtUsername').value)"
    HTML:
    For your php
    
    $xajax->registerFunction("ValidateUsername ");
    
    function ValidateUsername ($username) {
    	$objResponse = new xajaxResponse();
    		
    	/*Whatever you want here, including your validations */
    	$message = 'Something';
    		
    	$objResponse->addAssign('informationDiv','innerHTML',$message);
    	$objResponse = debug($objResponse, 'debug');	
    }
    
    PHP:
    It's a really interesting way to use RegEx for exemple in form validations. xAjax is really a good library for doing ajax, the xajaxResponse class permits a lot of thing. For exemple, you can use addScript to add to the response a couple of events like interface events(closing a popup, switching values of a field, throwing other ajax request, etc.....).

    In other words, you can use litteraly use php functions within javascript. Here's a link to the project : xajaxproject.org. It took me 10 minutes to get ready to work with it.
     
    pfek, Jul 8, 2007 IP
  5. ansi

    ansi Well-Known Member

    Messages:
    1,483
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    100
    #5
    it would be laggy as hell though. sending the request every time a character is input.
     
    ansi, Jul 8, 2007 IP
  6. oo7ml

    oo7ml Well-Known Member

    Messages:
    656
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    105
    #6
    thanks guys
     
    oo7ml, Jul 9, 2007 IP
  7. pfek

    pfek Member

    Messages:
    98
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    45
    #7
    OnChange != onKeyUp or Down :)
     
    pfek, Jul 9, 2007 IP