views:

1475

answers:

5

I'm toying with the new autocomplete in jQuery 1.8-UI. I've provided data in the following format

["val1", "val2", "val3"]

This is coming from a stored procedure but output as a string. For some reason this doesn't work at all, however, if I supply the same data using a javascript variable

var data = ["val1", "val2", "val3"];

Then this works fine.

<script type="text/javascript">
  $(function()
    $("#txtClient").autocomplete({
      source: "/intranet/common/scripts/IntranetLists.aspx?ListType=C"
    });
  });
</script>

I've got a page which supplies whatever data I want using query strings. It's more temporary, but it worked when I previously used bassistence's autocomplete.

Any ideas?


EDIT

The source simply outputs an entry on separate lines. Now the output does it with JSON format. What I don't understand is how the input provides the data as a query to the source of data. As I say, I'm using a script which should get called every time I enter a new key.

Here's the code I've got (take into account this worked fine with a third-party autocomplete plugin)

<%
  Dim MyCmd As New dbExact("proc_Intranet_Lists")
  MyCmd.cmd.Parameters("@List").Value = Request.QueryString("ListType")
  If Request.QueryString("Top") <> Nothing Then
    MyCmd.cmd.Parameters("@Top").Value = Request.QueryString("Top")
  End If
  MyCmd.cmd.Parameters("@Code").Value = Request.QueryString("term")
  MyCmd.cmd.Connection.Open()

  Dim results As New StringBuilder()
  results.Append("[")
  Dim dr As SqlDataReader = MyCmd.cmd.ExecuteReader
  If dr.HasRows Then
    While dr.Read
      results.AppendLine("'" + dr(0).ToString() + "',")
    End While
  Else
    results.Append("None Found")
  End If
  results.Remove(results.Length - 2, 2)
  results.Append("]")
  Response.Write(results.ToString())
  results = Nothing
  MyCmd.cmd.Connection.Close()
  MyCmd = Nothing
%>

The documentation for the new autocomplete doesn't state anywhere that the query string passed is actually called "term" (which I found out from the search.php file). I'm doing this in VB.NET.

+1  A: 

Your example isn't really clear enough. But if you would use php to fill the autocomplete variables I would just echo it in the javascript:

Js:

var data = <?php echo $autocomplete ?>;

PHP

$autocomplete = '["val1", "val2", "val3"]';

But I'm not sure if this is the answer you are looking for.

RJD22
Sorry, it's just an aspx page that's outputting the data in the format I said. This should be independent of the implementation.
Kezzer
could you post some more code of what you are trying to do?
RJD22
+2  A: 

Realistically, I should write a tutorial up for this because there's not much documentation around. If you want to use jQuery's new Autocomplete in jQuery-UI 1.8 then here's how you do it.

Personally, I used a generic web handler. I'm under the assumption these are better because they don't go through the regular request pipeline and instead only have two "elements", a property, and a sub-routine called ProcessRequest.

The way I do it is I've written a stored procedure which takes set arguments to determine what autocomplete I want. For example, if I want to use the autocompleter to list some countries, or I want to use it to list the names of employees, then I pass a certain query string to determine what I want back. This makes it very flexible.

<%@ WebHandler Language="VB" Class="Autocomplete" %>

Imports System
Imports System.Web
Imports System.Collections.Generic
Imports System.Web.Script.Serialization

Public Class Autocomplete : Implements IHttpHandler

  Public Class AutocompleteItem
    Public id As String
    Public value As String
  End Class

  Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    context.Response.ContentType = "text/plain"

    Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("YourConnectionString").ToString)
    Dim cmd As New SqlCommand("YourStoredProcedure", conn)
    cmd.CommandType = CommandType.StoredProcedure
    With cmd.Parameters
      .Add(New SqlParameter("@List", 22, 10, 1, False, 0, 0, "", 512, context.Request.QueryString("ListType")))
      .Add(New SqlParameter("@Code", 22, 12, 1, False, 0, 0, "", 512, context.Request.QueryString("term")))
      .Add(New SqlParameter("@Top", 16, 0, 1, False, 0, 0, "", 512, context.Request.QueryString("Top")))
    End With
    conn.Open()

    Dim results As New StringBuilder()
    Dim dr As SqlDataReader = cmd.ExecuteReader
    Dim items As New List(Of AutocompleteItem)
    Dim serializer As New JavaScriptSerializer()

    While dr.Read
      Dim autocomplete As New AutocompleteItem
      autocomplete.id = dr(0)
      autocomplete.value = dr(1)
      items.Add(autocomplete)
    End While

    Dim arrayJson As String = serializer.Serialize(items)
    context.Response.Write(arrayJson)
    conn.Close()
  End Sub

  Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
      Return False
    End Get
  End Property
End Class

I'm sure there's many other ways of doing this, but this is just what worked for me. I use the AutocompleteItem CDT because the named variables are what are used in jQuery's Autocomplete. By default, it uses id and value. You can specify anything else you want, but then you have to go and format your items yourself using the events provided in jQuery.

Fortunately .NET lets you serialize the data, but you can do so in PHP as well using json_encode. You can find the PHP example in the jQuery UI download.

Finally, here's the jQuery I used. I have a zero delay because it's a fast, local server.

<script type="text/javascript">
    $(function() {
      $("#txtClient").autocomplete({
        source: "/intranet/common/scripts/Autocomplete.ashx?ListType=Addresses",
        minLength: 2,
        delay: 0
      });
    });
</script>

Hopefully this will help you when using jQuery UI 1.8's Autocomplete.

EDIT If anyone has any recommendations on how to improve the generic handler, feel free to showo me. I notice I'm re-instantiating the AutocompleteItem object each time, however if you don't do this it will keep the old values for some reason, despite re-initializing the variables with new values. Cheers.

Kezzer
A: 

Kezzer - in the example given you look for three variables from the query string inside the handler, yet only send in one from the script. Am I missing something, or is this just an oversight? Apart from that, it's an excellent and concise response to something (autocompletes) that seems to be puzzling a lot of people.

mafbailey
+3  A: 

I found the JSON format pretty simple. You can check out the responses in firebug using the demo on this page : http://jqueryui.com/demos/autocomplete/#event-change .. here's one example :

[ 
{ "id": "Erithacus rubecula", "label": "European Robin", "value": "European Robin" }, 
{ "id": "Cercotrichas galactotes", "label": "Rufous-Tailed Scrub Robin", "value": "Rufous-Tailed Scrub Robin" }, 
{ "id": "Irania gutturalis", "label": "White-throated Robin", "value": "White-throated Robin" }, 
{ "id": "Turdus migratorius", "label": "American Robin", "value": "American Robin" }
]
Russell
Cool example, thanks, this helped me get the jquery-ui autocomplete finally working on my project.
Tim
A: 

$( "#someid" ).autocomplete({ source: "something.php(aspx)?param1=param1&param2=param2&param3=param3", minLength: 1, select: function( event, ui ) { alert( "value: " + ui.item.value + " , id: " + ui.item.id ); } });

baku