0

I've used Simon Whatley's code for the autocomplete plugin. Now, I need help in parsing a jSON data. Here is my code:

    $("#country").autocomplete("data/country.cfm",{
        minChars:1,
        delay:0,
        autoFill:false,
        matchSubset:false,
        matchContains:1,
        cacheLength:10,
        selectOnly:1,
        dataType: 'json',
        extraParams: {
                format: 'json'
        },
        parse: function(data) {
            var parsed = [];
            for (var i = 0; i < data.length; i++) {
                 parsed[parsed.length] = {
                data: data[i],
                value: data[i].NAME,
                result: data[i].NAME
                 };
            } 
            return parsed;
        },
        formatItem: function(item) {
            return item.NAME;
        }
   });

For example, I get this as my jSON string:

[{"name":"country1"},{"name":"country2"},{"name":"country3"}]

What I like to get as results, of course, are the values country1, country2, country3. However, what I get right now in the textbox when I type (e.g. I type "cou") is "undefined". If I click that, what shows in the textfield is the whole string [{"name":"country1"},{"name":"country2"},{"name":"country3"}].

I've also tried these but still not working: jquery autocomplete, how to parse a json request with url info? jquery autocomplete with json response

Help please. Thanks!

1 Answer 1

0

You can just simply use

var countries = JSON.parse(data);

Since you're using jQuery though, it's a bit safer to use jQuery.parseJSON() in case the browser doesn't have a native parser:

var countries = jQuery.parseJSON(data);
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Andrew! Thanks for the response. I tried your suggestion, but still it didn't work. This is what I get. When I type in the text field, I get "undefined" as search result. When I click that, the whole json string appears in the field. What could be the problem? Thanks.
Hi! I found out that Simon's autocomplete plugin expects results to be on individual lines and not in jSON format. See stackoverflow.com/questions/5100047/… Thanks!

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.