Skip to main content

Facebook like search box with auto complete using jquery, ajax and Asp.net



Hello
Today I am going to show how to create a simple asp.net code through which you can build a Facebook like search  



Step 1
Creating the required tables in database
Create a tale in database through we are going to fetch data and display result
CREATE TABLE [dbo].[test_auto_complete](
      [uid] [int] IDENTITY(1,1) NOT NULL,
      [username] [varchar](30) NULL,
      [email] [varchar](100) NULL,
      [media] [varchar](200) NOT NULL,
      [country] [varchar](200) NOT NULL
)
Insert some data in datbase you have just created .

Step 2
Now create a asp page in vs and add the following section in the head seaction
1)  Ajax funtion and javascript
<script type="text/javascript">
    $(function () {
        $(".search").keyup(function () {
            var inputSearch = $(this).val();
            var dataString = 'searchword=' + inputSearch;
            if (inputSearch != '') {
                $.ajax({
                    type: "POST",
                    url: "Search.aspx",
                    data: dataString,
                    cache: false,
                    success: function (html) {
                        $("#divResult").html(html).show();
                    }
                });
            } return false;
        });

        jQuery("#divResult").live("click", function (e) {
            var $clicked = $(e.target);
            var $name = $clicked.find('.name').html();
            var decoded = $("<div/>").html($name).text();
            $('#inputSearch').val(decoded);
        });
        jQuery(document).live("click", function (e) {
            var $clicked = $(e.target);
            if (!$clicked.hasClass("search")) {
                jQuery("#divResult").fadeOut();
            }
        });
        $('#inputSearch').click(function () {
            jQuery("#divResult").fadeIn();
        });
    });
</script>

2)  Html Part

<div class="contentArea">
<input type="text" class="search" id="inputSearch" /> Ex: manish, m,<br />
<div id="divResult">
</div>
</div>


3)   Style for serach result

<style type="text/css">
       body{
              font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
       }
       .contentArea{
              width:600px;
              margin:0 auto;
       }
       #inputSearch
       {
              width:350px;
              border:solid 1px #000;
              padding:3px;
       }
       #divResult
       {
              position:absolute;
              width:350px;
              display:none;
              margin-top:-1px;
              border:solid 1px #dedede;
              border-top:0px;
              overflow:hidden;
              border-bottom-right-radius: 6px;
              border-bottom-left-radius: 6px;
              -moz-border-bottom-right-radius: 6px;
              -moz-border-bottom-left-radius: 6px;
              box-shadow: 0px 0px 5px #999;
              border-width: 3px 1px 1px;
              border-style: solid;
              border-color: #333 #DEDEDE #DEDEDE;
              background-color: white;
       }
       .display_box
       {
              padding:4px; border-top:solid 1px #dedede;
              font-size:12px; height:50px;
       }
       .display_box:hover
       {
              background:#3bb998;
              color:#FFFFFF;
              cursor:pointer;
       }
</style>


Now create a name Search.aspx which we will call from textbox via Ajax to get result .this page will have all database connection coding.
Search page .cs page code
public partial class Search : System.Web.UI.Page
{
    SqlConnection ora = new SqlConnection("Data Source=192.168.1.1;Initial Catalog=database;Persist Security Info=True;User ID=usernane;Password=password");
    SqlCommand cmd;
    SqlDataReader dr;

    protected void Page_Load(object sender, EventArgs e)
    {
        String q = Request.Params[0];
        ora.Open();
      //  cmd = new SqlCommand("select media,username,email,country from test_auto_complete where username like '%"+q+"' or email like '%"+q+"'", ora);
        cmd = new SqlCommand("select media,username,email,country from test_auto_complete where username like '%" + q + "%' or email like '%" + q + "%'", ora);
        try                                                                                            
        {
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                string media = dr.GetValue(0).ToString();
                string username = dr.GetValue(1).ToString();
                string email = dr.GetValue(2).ToString();
                string country = dr.GetValue(3).ToString();
                Response.Write("<div class='display_box' align='left'><img src='" + media + "' style='width:50px; height:50px; float:left; margin-right:6px;' /><span class='name'>" + username + "</span>&nbsp;<br/>" + email + "<br/><span style='font-size:9px; color:#999999'>" + country + "</span></div>");
            }

        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
        ora.Close();
    }
}

Online Demo
You can view an online demo at this link Online Demo

You can download complete project  code from here Click here


Comments

  1. how to use it for gtting multiple value in single textbox

    ReplyDelete
    Replies
    1. hello
      you can concanicate result into a string and can show in textbox

      Delete
  2. very good ..tank you so much

    ReplyDelete
  3. Muy bueno felicitaciones y gracias por compartirlo! Saludos desde Argentina

    ReplyDelete
  4. When using asp Button for submit then Showing these error

    The state information is invalid for this page and might be corrupted.

    ReplyDelete
    Replies
    1. hey

      Use below at page directives, this will solve your problem

      EnableViewStateMac ="false" EnableSessionState="True" EnableEventValidation ="false" ValidateRequest ="false" ViewStateEncryptionMode ="Never"

      Delete
    2. Sir Problem is as it is Please Help me out your coding is working awesome but this issue give me big Headque please give me solution

      (When using asp Button for submit then Showing these error

      The state information is invalid for this page and might be corrupted.)

      Delete
    3. hello put you button in Updatepanel like below





      Delete
    4. This comment has been removed by the author.

      Delete
    5. put your button in UpdatePanel

      asp:UpdatePanel ID="UpdatePanel1" runat="server"
      ContentTemplate>
      asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
      ContentTemplate
      asp:UpdatePanel

      Delete
    6. Please try at least one time i done this things but not working sir pleases do it for once for me

      Delete
    7. singhkaruna1818@gmail.com

      Delete
    8. when using textbox value in code page on button clic then its error is showing

      Delete
    9. Its Not working when i use the input box on code page on Button Click Event nothing happen Please check your mail

      Delete
    10. What Happen Sir You didint Reply me

      Delete
    11. sir what happen you solved that?

      please reply asap

      Delete
  5. Beginner C#, jQuery, SQL Server, ASP.NET MVC, LINQ and much more..

    Beginner Programming Tutorials

    ReplyDelete
  6. I have apply all potion , still i am facing problem ..
    click using asp Button for submit then Showing these error

    The state information is invalid for this page and might be corrupted.

    ReplyDelete
  7. How can you add separate links to the search results to redirect them to a specific page like facebook

    ReplyDelete
  8. on clicking searched data how can i open whole record of that from database...means display-box div can act as a link

    ReplyDelete
  9. thanks sir.should i send my code please can u help me

    ReplyDelete
  10. sir,this code work on local but on server

    ReplyDelete

Post a Comment