Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a jquery which retrieves the values from the database using ajax and webmethod and it goes as follows
JavaScript
$(document).ready(function() {
        SearchText();
    });
function SearchText() {
   $(".autosuggest").autocomplete({
            source: function(request, response) {
            $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "InsertPage.aspx/GetAutoCompleteData",
                    data: "{'username':'" + document.getElementById('name').value + 
                        "'}",
                    dataType: "json",
                    success: function(data) {
                        response(data.d);
                    },
                    error: function(result) {
                        alert("Error");
                    }
                });
            }
        });
    }
</script>

and the web method is

C#
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
    List<string> result = new List<string>();
    using (SqlCommand cmd = new SqlCommand("select DISTINCT UserName from student_details
           where UserName LIKE '%'+@SearchText+'%'", con))

    {
        con.Open();
        cmd.Parameters.AddWithValue("@SearchText", username);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            result.Add(dr["UserName"].ToString());
        }
    } 
}


the textbox in which the ajax is used is

ASP.NET
<asp:TemplateField HeaderText="Student Name">
     <ItemTemplate>
        <input type="text" id="name" class = "autosuggest" />
   </ItemTemplate>
</asp:TemplateField>


Now, I have an addrow button also which adds the row dynamically
C#
 protected void addrowcontrols(bool isAdd)
    {

        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[0].FindControl("name");
                    drCurrentRow = dtCurrentTable.NewRow();
                    //drCurrentRow["RowNumber"] = i + 1;


                    dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                    rowIndex++;
            }
            if (isAdd == true) dtCurrentTable.Rows.Add(drCurrentRow);
            else dtCurrentTable.Rows.RemoveAt(dtCurrentTable.Rows.Count - 1);

            ViewState["CurrentTable"] = dtCurrentTable;

            Gridview1.DataSource = dtCurrentTable;
            Gridview1.DataBind();
        }
    }
}




If I debug the program , the value in this ajax textbox is coming as null and the output in the textbox is coming empty and the error message is Object reference not set to an instance of an object as a result I am not able to go further and store the value in the database .

Please Help me I know the question is big but I have stuck in this for past 3 days.
Posted
Updated 7-Apr-13 20:26pm
v2
Comments
vijay__p 8-Apr-13 3:00am    
You can not get HTML controls server side, to get control and its value at server side control must be marked as runat="server".
Member 8673923 8-Apr-13 3:03am    
Sir, I already tried this but after I added this ,the control is not going inside the web method only i.e the ajax is not loading at all
vijay__p 8-Apr-13 5:37am    
You have to use ClientID proerty of server control to attach "autocomplete".
Use $('#<%=name.ClientID %>').autocomplete....
Member 8673923 8-Apr-13 5:48am    
An error is coming that The name 'name' does not exist in the current context???
vijay__p 8-Apr-13 5:53am    
Dear.. error is coming because you are trying to access control outside of GridView, which will not be possible. you need to write this JavaScript in GridView/Beside Textbox only to make it work.

When you do work like this, you have to test all the JSON values first using a JSON validator,

1. So you test all your input first in the jQuery
2. test the web service, make sure it return a JSON String or autocomplete values
3. Test your Jquery ResponseText, to make sure the data arrived intact, you may have to encode the strings, and decode them in Jquery

var firstName = document.getElementById('name').value;
var jsonData = "{'username':'" + firstName + "'}";
alert(jsonData); // Validate this JSON to make sure it's right
$.ajax({
     type: "POST",
     contentType: "application/json; charset=utf-8",
     url: "InsertPage.aspx/GetAutoCompleteData",
     data: jsonData,
     dataType: "json",
     error: function (xhr, status, error) {
        alert(xhr.responseText); //This will give you the stack error from the web service
     },     
     success: function(responseText) {
        alert(responseText.d) // Validate this return value in Json Validator 
        var objB = jQuery.parseJSON(responseText.d);
        //var exitCode = objB.exitCode; //Get the value from the Json Result
         
     },
     
});


The web service has to return a valid JSON string back to the JQuery, so you debug the web service, and test the string before sending it back to Jquery. I can't help you with the web service, I would of wrote it different, and just hand build my return values, so I have more control over the process.

JSON Validator
http://jsonlint.com/[^]
 
Share this answer
 
Replace
C#
data: "{'username':'" + document.getElementById('name').value +
                        "'}",

with
C#
data: "{username:'" + document.getElementById('name').value +
                        "'}",
 
Share this answer
 
Comments
Anuja Pawar Indore 9-Apr-13 10:30am    
what is difference between both lines
Shiva Sai 10-Apr-13 1:06am    
In previous one username is enclosed with brackets.
Here in this case that might not be the actual reason for getting the error but there may be a chance.Actually 2nd one is the exact way of sending the data.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900