views:

144

answers:

3

I do not know what is wrong with this code. alert shows that data has returned from web service but auto-complete still not showing data. I am using ASP.net 2.0 and google jquery link

  $(document).ready(function() {
         $.ajax({
            type: "POST",
            url: "http://localhost/WebService/Service.asmx/getlist2",
            dataType: "json",
            data: "{}",


            contentType: "application/json; charset=utf-8",
            success: function(data) {
         alert("getlist 2");
             alert(data);

                $('#project1').autocomplete({
                    minLength: 2,
                    source: data,

                    focus: function(event, ui) {
                        $('#project1').val(ui.item.TagName);
                        alert(ui.item.TagName);//no alert is fired here
                        return false;
                    },
                    select: function(event, ui) {
                        $('#project1').val(ui.item.TagName);
                        //$('#selectedValue').text("Selected value:" + ui.item.TagID);
                        return false;
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
     });

and web service method

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Tag> getlist2()
{
    <Tag> tagscollection = new  EntitiesCollection<Tag>();
    ProcessTagList getlisttags = new ProcessTagList();

    string strtag = "";

    Tag tag = new Tag();
    tag.TagName =   strtag;
    tag.UniqueName =   strtag;
    getlisttags.OTag = tag;
    getlisttags.Invoke();
    tagscollection = getlisttags.OTagsCollection;


    ;
      List<Tag> a = new List<Tag>();
    foreach(Tag tagc in tagscollection)
    {
        a.Add(tagc);
    }


    return a;


}

data shown in firebug is:

[{"__type":"myproject.Common.Tag","TagID":"21abf6b1-6d45-41e5-a39b-006e621eeb22","UniqueName":"dotnet","TagName":"dotnet","CreatedAt":"\/Date(1255108286850)\/"}]

this jquery code shows dropdown list from the webservice used with first jquery example.

$("#tbAuto").autocomplete({
    source: function(request, response) {
        $.ajax({
            url: "http://localhost/myproject/Service.asmx/getlist2",
            data: "{}",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
          //  dataFilter: function(data) { return data; },

            success: function(data) {
                response($.map(data, function(item) {
                    return {
                        value: item.TagName
                    }
                }))
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(errorTrown);
            }
        });
    },
    minLength: 0
});
+1  A: 

You need to set the autocomplete source property to a collection\array. I do not think your returned data is one although it may contain one. You also need to rename your server side object to provide a label value pair. e.g

{ "id": "1", "label": "StackOverflow", "value": "SO" }

Check the examples out here and use firebug to see how they return the json data.

From the docs

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

Can you paste the json response.

redsquare
[{"__type":"myproject.Common.Tag","TagID":"21abf6b1-6d45-41e5-a39b-006e621eeb22","UniqueName":"dotnet","TagName":"dotnet","CreatedAt":"\/Date(1255108286850)\/"},{"__type":"myproject.Common.Tag","TagID":"b6c3adb4-f7b5-4a2c-829c-0bde935a2689","UniqueName":"Foundation,ASP.NET,WCF,","TagName":"Foundation,ASP.NET,WCF,","CreatedAt":"\/Date(1257098846373)\/"}]
klusner
i ve pasted two rows here.
klusner
@klusner - youll need to amend your server side object to give the autocomplete a structure that it can work with e.g the one I posted in my answer with label and value properties
redsquare
@redsquare i will show another piece of jquery code that do show dropdownlist but actuall shows all list rather than showing specific one that had been typed.check the question edited
klusner
i ve pasted json response here anybody has idea how this code will work.
klusner
thanks folks I am little late to response this question. actually i was not returing data according to id, label, value format side + webservice was inside main project directory. I have placed web sevice outside the root directory of the project. the reason was Urlrewrite library.
klusner
+1  A: 

Okay, I know you are using asp.net and my example is based on PHP and MySQL, but since your problem seem to be about the JSON format autocomplete is expecting, I am posting anyway.

Get the latest files from the jQuery UI page. The autocomplete need UI Core, UI Widget and UI Position from the base package. You also need the autocomplete widget itself.

This example works well for me:

The HTML:

<div>
    <input id="cities" />
</div>

The script part:

(It sends the search variable to cities.php as cities.php?term=)

$(function() {
  $("#cities").autocomplete({
    source: "backend/cities.php",
    minLength: 2,
    select: function(event, ui) {
      // perhaps do something with these?
      region = ui.item.id;
      country = ui.item.label;
      city = ui.item.value;
      secret = ui.item.secret;
   }
});
});

The PHP in cities.php:

(The variables id, label and value need to be used. Label is used to populate the drop down list. Value is entered into the input box when the label value is clicked in the list).

// important to set header with charset
header('Content-Type: text/html; charset=utf-8');
$term = $_POST["term"];
// some database stuff removed
// loop it through and build array
$n = 0;
    while ($row = $q->fetch()) {
        $row_array[$n]['id'] = $row['City'];
        $row_array[$n]['label'] = $row['Country'];
        $row_array[$n]['value'] = $row['Region'];
        $row_array[$n]['secret'] = 'blabla';
        $n++;
    }
    // encode it to json format
    echo json_encode($row_array);

The JSON sent back:

(When ?term=new york)

[{"id":"New York","label":"United States","value":"New York","secret":"blabla"},{"id":"Minnesota","label":"United States","value":"New York Mills","secret":"blabla"},{"id":"New York","label":"United States","value":"New York Mills","secret":"blabla"}]

So, to recap:

  • By default, it sends the variable "term" with the search word to the backend page.
  • It needs "id", "value" and the "label" variables to be sent back.
  • By default the drop down list is populated with the "label"-values.
  • By default, clicking in the list will fill out the input box with "value".
  • You can put additional variable names and make something with them, but the three above is needed.
  • The JSON syntax need to look as provided above.

I hope it helps.

Mattis
A: 

Your data is not showing up because autocomplete expects the data in a certain way (id,label and value). See other answers as well.

Your getlist2 functions gives another structure of data (__type, TagID,UniqueName,TagName and CreatedAt).

Try to modify getlist2 to give back the proper syntax.

Your last change to the topic start (jquery autocomplete + .ajax) looks alright, what is not working on that piece of code?

PoweRoy
why the downvote
PoweRoy