Navigetion

Monday, March 18, 2013

Auto complete using jQuery & Ajax

The Idea

You want to ask the user to enter a name in the input text field, so that the moment the user types the first character of a name, a suggestion box will appear that displays all the names beginning with the character typed. You also want the names displayed in the suggestion box to have a hovering effect – so that they become highlighted on moving the mouse pointer over them – and the clicked name to be inserted in the input text field.

Implementation

Let’s create an HTML file that displays a label: ‘Enter userid’ and an input text field. Below the input text field, we create two empty div elements that are assigned the class names: listbox and nameslist respectively. The HTML file may appear as shown below:

Enter user id

The div element of class listbox will be used for displaying a box and the div element nameslist will be used for displaying the names with hovering effect. We define the style rules to be applied to the two div elements in the style sheet file: style.css as shown here:

.listbox {
    position: relative;
    left: 10px;
    margin: 10px;
    width: 200px;
    background-color: #000;
    color: #fff;
    border: 2px solid #000;
}
.nameslist {
    margin: 0px;
    padding: 0px;
    list-style:none;
}
.hover {
    background-color: cyan;
    color: blue;
}

The jQuery code to now make our suggestion box appear when the user types the first character in the input text field, and to make the clicked name (in the suggestion box) to appear in the input text field automatically, is as shown here:

$(document).ready(function() {
    $('.listbox').hide();
    $('.userid').keyup(function () {
        var uid = $('.userid').val();
        var data='userid='+uid;

        $.ajax({
        type:"POST",
        url:"autocomplete.php",
        data:data,
        success:function(html) {
            $('.listbox').show();
            $('.nameslist').html(html);
            $('li').hover(function(){
                $(this).addClass('hover');
            },function(){
                $(this).removeClass('hover');
            });
            $('li').click(function(){
                $('.userid').val($(this).text());
                $('.listbox').hide();
            });
      }
    });
    return false;
  });
});

The script file autocomplete.php, on the server, is designed to send the list of names as response, and it should look like this:

    echo '
  • Jackub
  • '; echo '
  • Jenny
  • '; echo '
  • Jill
  • '; echo '
  • John
  • ';

    Check out your site now. Try typing a name begins with 'J'.
    Booya! If everything's goes well I believe you will get a pop-up with a list of name begins with 'j'.

    Though this is not the best way of generating the autocomplete menu and obviously we will generate the autocomplete menu using data from the database, but I believe you get the idea. I will make another post where I'm going to show how can we can grab the information(data) from the database and fill the autocomplete list with it. Knock me out if you have any question. Till then bye bye.

    Validating an Email Address usning jQuery & Ajax

    The Idea

    You want the user to enter his email address and you want to use a server-side script to confirm that it is a valid email address. This means that it must consist of alphanumericals, no symbols other than - and _ , plus it must contain both symbols . and @. If the email address is invalid, an error message should be displayed to the user.

    Implementation

    Let’s make an HTML file that displays a label: ‘Enter email address’ and an input text field and a submit button. The HTML file may appear as shown below:

    Enter email address

    We can see in above HTML file that the input text field is assigned the class name emailadd for the purpose of accessing it via jQuery code. Following the input text field, is an empty span element of class error. The text to this span element will be assigned from the server generated response, if the user enters an invalid email address.

    In order to specify width to the label, input text field and color to the error message, we will make use of the style rules written in the style sheet file from the solution we used in 8-3. The jQuery code to invoke the server side script: validatemail.php for validating the email address entered by the user is as shown below:

    $(document).ready(function() {
        $('.error').hide();
        $('#submit').click(function () {
            var em = $('.emailadd').val();
            var data='emailadd='+em;
            $.ajax({
                type:"POST",
                url:"validatemail.php",
                data:data,
                success:function(html) {
                    $('.error').show();
                    $('.error').text(html);
                }
            });
            return false;
        });
    });
    

    The script file validatemail.php, on the server, is designed to check whether the email address of the user is valid or not:

    
    

    SOME SAMPLE I/O AND RESULT

    InputResult/Output
    john-123@yahooNot accepted/Invalid email address
    john-123@yahoo.comAccepted

    Validating a User Name Using Ajax

    The Idea

    You want to ask the user to enter a name and you want to use a server-side script to confirm that the field is not left blank. If the user does not enter anything in the name field, then he should get an error message.

    Implementation

    Let’s start by creating an HTML file that displays a label: ‘Enter your Name’ and an input text field and a submit button. The HTML file may appear as shown below:

     
      
    Enter your Name

    You can see here that the input text field is assigned class name uname for the purpose of accessing it via jQuery code. Following the input text field is an empty span element of class error. The text to this span element will be assigned from the server generated response – if the user leaves the input text field blank.

    In order to specify a width to the input text field label, and a color to the error message, we need to write some style rules in the style sheet file:

    .label {float: left; width: 120px; }
    .uname {width: 200px; }
    .error { color: red; padding-left: 10px; }
    #submit { margin-left: 125px; margin-top: 10px;}
    

    The jQuery code to invoke the server side script is below, which passes to validateuser.php. the name entered by the user as a parameter, and displays an error message if the name is left blank by the user:

    $(document).ready(function() {
        $('.error').hide();
            $('#submit').click(function () {
                var name = $('.uname').val();
                var data='uname='+name;
                $.ajax({
                    type:"POST",
                    url:"validateuser.php",
                    data:data,
                    success:function(html) {
                        $('.error').show();
                        $('.error').text(html);
                    }
                });
            return false;
         });
    });
    

    The script file validateuser.php itself, is on the server, and is meant for checking whether the name of the user is not left blank. This code looks like this:

    
    

    Validating user name using a regular expression

    In the above solution, the user could enter anything when they were meant to be entering their user name – including symbols. So let’s improve the server side script so we will only accept names that consist of alphanumerical and underscore only. The script file validateuser.php can be modified as shown here to achieve this for us:

    
    

    SOME SAMPLE I/O AND RESULT

    InputResult/Output
    blankNot accepted/This field cannot be blank
    JohnAccepted
    John-123Not accepted/Invalid User Name
    John_123Accepted