1

I want to use Jquery autocomplete in my web application but encounter issues. I am developing my application in ASP.NET and JQuery.

Here's the part of the Autocopmlete 'succes' function:

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

My webservice returns the following JSON:

"[{"key":"Bread","value":"3"}]"

When I run it I get Javascript error:

Uncaught TypeError: Cannot use 'in' operator to search for '42' in [{"key":"bread","value":"3"}] 

It looks like that the returned JSON is not in the right format for the $.map function from what I can tell. Also the result might return several items, not just one as seen above.

Can anyone help me solve this issue. I am using JSON as the dataType and GET as the type in the Ajax call.

0

2 Answers 2

7

I simply suggest you instead of using any other method you can use :

success: function (data, status, xhr) {
    var jsonArray = JSON.parse(data);  // Normal way
}

Other way

success: function (data, status, xhr) {
    var jsonArray = $.parseJSON(data); // using jQuery
}

In this way it will be converted to a simple JavaScript object which you can easily manipulate on your UI/DOM.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I used your solution with a $.each loop and it works. I've needed to parse the result and then use the for each for put them in an array
Its a pleasure for me to help you.
Thanks, Ankur. So Idan's issue was that he was not calling the $.each method on an object? He was calling the method on just a string? I used your solution and it worked for me. When I printed out response (not using JSON.parse) in my app, I saw the actual content of the object (string type). However, after using JSON.parse(response), I saw [Object object], [Object object], ... with type object
0

You're right -- your JSON is an array which contains a single object. You're expecting just that object.

Try modifying your code like so:

success: function (data) {
  data = data[0]; 

3 Comments

From FireBug: data.d: "[{"key":"bread","value":"3"}]" $.map(data.d[0]): [Exception: TypeError: Cannot use 'in' operator to search for '0' in []
Now you're changing things. Is "[{"key":"bread","value":"3"}]" the value of data or data.d? What exactly is in data?
data.d = "[{"key":"bread","value":"3"}]" and data = d: "[{"key":"bread","value":"3"}]" (from firebug)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.