fpena06
fpena06

Reputation: 2426

jQuery autocomplete ajax TypeError

Not sure why I continue to get this error when trying to implement autocomplete with ajax source.

"Uncaught TypeError: Cannot read property 'length' of undefined" 

Here is my route in express.

exports.findAllIrds = function(req, res) {
    var name = req.query["value"];
    db.collection('employees', function(err, collection) {
        if (name) {
            collection.find({
                "value": new RegExp(name, "i")
            }, {
                value: 1,
                data: 1,
                _id: 0
            }).toArray(function(err, items) {
                res.jsonp(items);
                //console.log(req.query);
                //console.log(items);
            });
        } else {
            collection.find().toArray(function(err, items) {
                res.jsonp(items);
                console.log(req.query);
            });
        }
    });
};

If I browse to /receiversjson I get all my json as expected and when I browse /receiversjson?value=293589324 I get

[{"value": "2935893244","data": "D33HL3RH311911"}] as expected.

However when I try jquery autocomplete with the following code I get error.

$('.item-name textarea').autocomplete({
    serviceUrl: '/receiversjson',
    paramName: 'value',
    autoSelectFirst: true,
    onSelect: function(suggestion) {
        alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
    }
});  



Uncaught TypeError: Cannot read property 'length' of undefined

In chrome developer tools network tab I see "receiversjson?value=293589324" and when I click on it it open a page with my json.

[{
    "value": "2935893244",
    "data": "D33HL3RH311911"
}]

What am I missing or doing wrong?

enter image description here

Upvotes: 1

Views: 1430

Answers (1)

fpena06
fpena06

Reputation: 2426

My problem was the json respond wasn't including "suggestions:" my output was this

[
  {
    "value": "1999458647",
    "data": "A10GA8CW330293"
  }
]

JQuery Autocomplete was looking for this.

{
  "suggestions": [
    {
      "value": "1999458647",
      "data": "A10GA8CW330293"
    }
  ]
}

I currently got it working with this.

exports.findAllIrds = function(req, res) {
    var name = req.query["value"];
    db.collection('employees', function(err, collection) {
        if (name) {
            collection.find({"value": new RegExp(name, "i")},{value:1,data:1,_id:0}).toArray(function(err, items) {
                var myobj = {};
                var suggestions = 'suggestions';
                myobj[suggestions] = items;
                res.jsonp(myobj);
            });
        } else {
            collection.find().toArray(function(err, items) {
                res.jsonp(items);
                console.log(req.query);
            });
        }
    });
};

Upvotes: 3

Related Questions