1
$.ajax({
        type: "POST",
        url: "/webservices/AutoSuggestWebService.asmx/GetSuggestedRestaurants",
        data: "{'prefixText': '" + $('#ctl00_ctl00_cplMPBody_txtSearch').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            data = msg.d;
            alert(msg.d)
            $("#ctl00_ctl00_cplMPBody_txtSearch").autocomplete(data);
        }
    })

where data is

["some text","another some textz","huh just text"]

WS:

[WebMethod]
        public string GetSuggestedRestaurants(object prefixText)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            string json = js.Serialize(new RestaurantSearchHelper(DaoFactory).GetSearchSuggest(prefixText.ToString(), PageBase.CurrentCountry));
        }

but if i search by word "so" i don't get anything.

If ws return

[WebMethod]
        public string GetSuggestedRestaurants(object prefixText)
        {
            return  "Aeroplane dkhashd Apple Ambulance Border Crops Desalination Elephants  Parrot ";
        }

and js looks like

data = msg.d.split(" ");
alert(data)

then data looks like

Aeroplane,dkhashd,Apple,Ambulance,Border,Crops,Desalination,Elephants,Parrot

and autosuggest work. What is worng with first json if data is

["some text","another some textz","huh just text"]
senzacionale
  • 20,448
  • 67
  • 204
  • 316

1 Answers1

1

Your first error is that the text

{'prefixText': 'bla bla'}

is NOT valid JSON string. It could be correct object initializer in JavaScript, but it is wrong encoded JSON corresponds to http://www.json.org/ and RFC4627. Correct JSON string will be

{"prefixText": "bla bla"}

or the following

data: '{"prefixText": "' + $('#ctl00_ctl00_cplMPBody_txtSearch').val() + '"}'

in your case (with some small possible problems if $('#ctl00_ctl00_cplMPBody_txtSearch').val() has " or \ characters inside). I recommend you http://www.jsonlint.com/ site where you can validate any JSON data.

The next problem is on the server side. The ASMX web method should be like the following

[WebMethod]
[ScriptMethod (ResponseFormat = ResponseFormat.Json)]
public List<string> GetSuggestedRestaurants(string prefixText) {
    return new RestaurantSearchHelper(DaoFactory).GetSearchSuggest(
                   prefixText,
                   PageBase.CurrentCountry);
}

and the corresponding class should has [ScriptService] attribute.

I recommend you to use JSON.stringify method:

data: JSON.stringify({ prefixText: $('#ctl00_ctl00_cplMPBody_txtSearch').val() })

instead of manual JSON serialization. See details in my other answer which include link to the working demo project.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798