Ashish
Ashish

Reputation: 2564

jQuery autocomplete with asmx issue

I am having a strange issue. I am trying to use jQuery autocomplete with asmx web service. My JavaScript code is as:

$('#txtUsers').autocomplete('AjaxHandler.asmx/GetUserData', {
    width: 320,
    max: 5,
    minChars: 3,
    parse: function(data) {
        var items = data.d;
        var parsed = [];
        for (var i = 0; i < items.length; i++)
            parsed.push({
            data: [items[i]],
            value: items[i],
            result: [items[i]]
        });
        return parsed;
    }
});

and my web service code is:

[WebService]
[ScriptService]
public class AjaxHandler : WebService
{
    [WebMethod]
    public List<UserData> GetUserData(string q)
    {
        //My code here.....
    }
}

However my web method is not being called from autocomplete. However whenever I try to call the same web method from jQuery.ajax, it gets fired correctly. Any help?

Upvotes: 1

Views: 1201

Answers (2)

Andrew Orsich
Andrew Orsich

Reputation: 53685

I checked that autocomplete send get request, but you service accept only post requests. So, i see that you also found it.

I suggest to use simple HttpHandler, and return data as json using newton json serializer, because you web service retun 'wrapped' data. It should be very simple handler:

List<UserData> items = GetUserDataItems();
string json = JsonConvert.SerializeObject(items);

//retrun json to the client

Also at client code set dataType to json:

dataType: "json",

And parse like this:

parse: function (data) {
    return $.map(data, function (row, i) {
        return {
            data: row,
            value: row,
            result: row
        }
    });
},

Upvotes: 1

Dewfy
Dewfy

Reputation: 23634

Yes, I've stand with this problem also. Neither ScriptService nor ScriptMethod helps for autocomplete. The simplest work around is convert your .asmx into .ashx and manage return result as it is expected by AJAX plugin with help of JSON serializer.

Upvotes: 1

Related Questions