Sadiq Jaffer
Sadiq Jaffer

Reputation: 72

JQuery Selector with JSON

I'm trying to retrieve my JSON values to my autocomplete table row using the following:

Javascript:

 <script>
        $(document).ready(function () {
            var text2 = $("#Text2").tautocomplete({
                width: "500px",
                columns: ['id', 'title'],
                ajax: {
                    url: "products.json",
                    type: "GET",
                    data: function () {
                        return [{ test: text2.searchdata() }];
                    },
                    success: function (data) {

                        var filterData = [];

                        var searchData = eval("/" + text2.searchdata() + "/gi");

                        $.each(data, function (i, v) {
                            if (v.products.search(new RegExp(searchData)) != -1) {
                                filterData.push(v);
                            }
                        });
                        return filterData;
                    }
                },
                onchange: function () {
                    $("#ta-txt").html(text2.text());
                    $("#ta-id").html(text2.id());
                }
            });
        });
    </script>

products.json:

 {"products":[[{"id":"1","country":"Photobooks"},{"id":"2","country":"Cards"}]]}

and I'm getting this error: TypeError: v.products is undefined

Any help or suggestions will be appreciated.

Upvotes: 0

Views: 194

Answers (1)

Popnoodles
Popnoodles

Reputation: 28409

Given what products.json returns to the variable data, there is no v.products in your loop. There is data.products which is an array with one node which is an array of your results. Take a look:

{"products":
    [
        [
            {
                "id":"1",
                "country":"Photobooks"
            },
            {
                "id":"2",
                "country":"Cards"
            }
        ]
    ]
}

This will iterate through those results

success: function (data) {
    $.each(data.products[0], function (i, v) {
        // etc
    });
}

Demo

Upvotes: 1

Related Questions