Tuesday 15 July 2014

Asp.net C# Webmethod with jquery

I am using webmethod with Jquery.
CLIENT SIDE:
1. Include jquery like below example script 
<script type='text/javascript' src="http://code.jquery.com/jquery-1.11.1.min.js"/>  
2. I have a input box with id txttest.
<input type="text" id="txttest" class="autosuggest" /> 
3. Ajax call as below.  
  $.ajax({
       type: "POST",
       contentType: "application/json; charset=utf-8",
       url: "order_form.aspx/GetAutoCompleteData", 
       data: '{DocName: "' + $("#txttest").val() + '" }', 
       dataType: "json",
       success: function(data) { 
           //response(data.d);   
           alert('success');
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) { 
         alert(textStatus);
       } 
   }); 
4. On success you will get data from server [Example: response(data.d);]  
SERVER SIDE:
1. Example web method as below:
    [WebMethod]
    public static List<string> GetAutoCompleteData(string term)
    {
       List<string> result = new List<string>();
       OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
       string query = "SELECT * from gallery WHERE (unique_no LIKE '%" + NJS_Helper.FormatStringforDB(term) + "%') limit 5;";
       if (conn.State == ConnectionState.Open)
       conn.Close();
       conn.Open();            
       OdbcDataReader dataReader = new OdbcCommand(query, conn).ExecuteReader();
            if ((dataReader != null) && (dataReader.HasRows))
            {
                while (dataReader.Read())
                {
                    result.Add(dataReader["unique_no"].ToString());
                }
            }
      dataReader.Close();
      return result;
    }

No comments:

Post a Comment