Link to home
Start Free TrialLog in
Avatar of milindsaraswala
milindsaraswala

asked on

JQuery Auto Complete and ASP.net

I am very new to JQuery and I added JQuery Auto complete UI in my asp.net 2.0 application I have connected my application to SQL Server 2005. But I am getting error always.

Actually senerio is like this I have created DAL .xsd file on that I have created BLL file from that I have created webservice in that I have created parameterize function which I am passing to JQuery Auto Complete But it giving me error.

Following is the code used in APSX page
<script type="text/javascript">
        $(document).ready(function() {
          $("input#actorList").autocomplete({
            source: function(request,response){
            $.ajax({
                type: "POST",
                url: "../AutoComplete.asmx/GetCompletionActorList",
                dataType: "json",
                data: "{'actorName':" + request.term + "}",
                contentType: "application/json; charset=utf-8",
                success: function(data) {
                    response($.map(eval(data),function(item){
                      return{
                        label: item.Name,
                        value: item.Name
                      }
                    }));
                  }
                })
              },
              minLength: 2
            });
          });

    </script>

Open in new window


This is code in ASPX page in Form
<asp:TextBox ID="actorList" CssClass="tb" runat="server"/>

Open in new window


This is the code in webservice
  <WebMethod()> _
  Public Function GetCompletionActorList(ByVal Name As String) As String
    Dim sbActor As New StringBuilder()
    Dim actorAPI As New ActorBLL
    Dim actor As Q8movies.ActorDetailDataTable = actorAPI.GetActorDetailByActorName(Name)

    Try
      'sbActor.Append("[")
      For i As Integer = 0 To actor.Rows.Count - 1
        sbActor.AppendFormat("'{0}',", actor.Rows(i).Item("ActorName"))
      Next

      'Removes the extra ":"
      sbActor = sbActor.Remove(sbActor.Length - 1, 1)
      'sbActor.Append("]")
    Catch ex As Exception
      'Setup a breakpoint here 
      'to verify any exceptions raised.
      Dim exp As String = ex.ToString()
    End Try
    Return sbActor.ToString()
  End Function

Open in new window


But when run the application I did not get any error. But I check this with Fire Bug utility I found that following error in JSON
{"Message":"Invalid JSON primitive: Li.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

Kindly help me on this where I am doing mistake.
Avatar of leakim971
leakim971
Flag of Guadeloupe image

You set contentType as json. So the webservice need a method to unserialise the json request {actorName:<>}
I don't saw that in your code.

Back you need to return a json string as you set the dataType as json.

You may send html and return an array string
Avatar of milindsaraswala
milindsaraswala

ASKER

Thank you for the reply But actually as I say I am new to the JQuery can you change my code send me back. I will be really help for the same.
In you code, client side, replace line 9 data: "{'actorName':" + request.term + "}" by :

data: JSON.stringify({"actorName": request.term }),

Open in new window

I did the changes as per you told But there is something missing. I putting code attach with this and Image of out put with this
<script type="text/javascript">
        $(document).ready(function() {
          $("input#actorList").autocomplete({
            source: function(request,response){
            $.ajax({
                type: "POST",
                url: "../AutoComplete.asmx/GetCompletionActorList",
                dataType: "json",
                data: JSON.stringify({"actorName": request.term }),
                contentType: "application/json; charset=utf-8",
                success: function(data) {
                    response($.map(eval(data),function(item){
                      return{
                        label: item.Name,
                        value: item.Name
                      }
                    }));
                  }
                })
              },
              minLength: 2
            });
          });

    </script>

Open in new window

Screen.JPG
It work better no ? Please confirm the error is not the same.
Which .net framework are you using ?
I am using asp.net 2.0
Any thing more if you need. I can see the output in Fire bug but it is saying error missing ;
you should return an array, replace : response($.map(eval(data),function(item){
by :




response($.map(eval("[" + data + "]"),function(item){

Open in new window

another thing, you can replace
label: item.Name,
value: item.Name

by :

label: item,
value: item
Actually what I done in webservice as put [ before making array and ] array again I will put my code of webservice

and after changes of code give by you it is giving error missing ]
Webservice

<WebMethod()> _
  Public Function GetCompletionActorList(ByVal actorName As String) As String
    Dim sbActor As New StringBuilder()
    Dim actorAPI As New ActorBLL
    Dim actor As Q8movies.ActorDetailDataTable = actorAPI.GetActorDetailByActorName(actorName)

    Try
      sbActor.Append("[")
      For i As Integer = 0 To actor.Rows.Count - 1
        sbActor.AppendFormat("'{0}',", actor.Rows(i).Item("ActorName"))
      Next

      'Removes the extra ":"
      sbActor = sbActor.Remove(sbActor.Length - 1, 1)
      sbActor.Append("]")
    Catch ex As Exception
      'Setup a breakpoint here 
      'to verify any exceptions raised.
      Dim exp As String = ex.ToString()
    End Try
    Return sbActor.ToString()
  End Function

Script

<script type="text/javascript">
        $(document).ready(function() {
          $("input#actorList").autocomplete({
            source: function(request,response){
            $.ajax({
                type: "POST",
                url: "../AutoComplete.asmx/GetCompletionActorList",
                dataType: "json",
                data: JSON.stringify({"actorName": request.term }),
                contentType: "application/json; charset=utf-8",
                success: function(data) {
                    response($.map(eval("[" + data + "]"),function(item){
                      return{
                        label: item.Name,
                        value: item.Name
                      }
                    }));
                  }
                })
              },
              minLength: 2
            });
          });

    </script>

Open in new window

Ok, I look the firebug dump, the bracket is not visible.

So just update from my previous comment :


success: function(data) {
                    response($.map(eval(data),function(item){
                      return{
                        label: item,
                        value: item
                      }
                    }));
                  }

Open in new window

Thank you very much. It start working like charm in firefox. I just remove <b>[]</b> from my webservice and your code in my client side
 1: response($.map(eval("[" + data + "]"),function(item){

But still it is not working in Internet explorer it is giving error <b>'JSON' is undefined</b>
Kindly also tell me how to write CSS for handling drop down font selected color. In short I need some help on CSS for autocomplete.

Thank you very much for giving time really appriciate
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Wow you are real hero it start working very good on both. Just last help on CSS please. So I can close this ticket.
>Just last help on CSS please. So I can close this ticket.

Why not a new question ? And don't forget to add the css zone ?
Really Leakim was very supportive. He solved my solution very fast with no hesitation. I really appreciate him
Thanks a lot for your comments and for the points! I will do my best to answer your next questions!
very good answer