theGreenCabbage
theGreenCabbage

Reputation: 4845

jQuery Autocomplete Appending Value to URL

I am currently implementing an autocomplete module to my site which parses weather information from Weather Underground

$(function(request) {
    var cities = []; // setup empty array
    $.ajax({
      url : "http://autocomplete.wunderground.com/aq?",
      query : request.term,
      dataType : "json",
      success : function(parsed_json) {
        for(i = 0; i < parsed_json['RESULTS'].length; i++) {
            cities.push(parsed_json['RESULTS'][i]['name'])
        }
      }
    });
    $( "#tags" ).autocomplete({
        source: cities
    });
});

Essentially, I populate an array called cities with the city names when the person types in their search query and it would send s request to Weather Underground's auto-complete API.

Using the variable query : request.term, I try to append the key value query=[search term] to the end of the url. However, when I check the console, it seems the request.term is always empty.

My question is - why is my input parameter empty for the text box?

The text box' id is tags.

Upvotes: 0

Views: 709

Answers (2)

aebabis
aebabis

Reputation: 3705

You need to initialize the widget on page load, then update its Array as you type. Since ajax is asynchronous, you need to update the autocomplete array inside the success callback

$(function () {
    var $input = $('#tags');
    $input.autocomplete({
        source: [] // Initially empty
    }).on('input', function () {
        $.ajax({
            url: "http://autocomplete.wunderground.com/aq?",
            data: { "query": $input.val() },
            dataType: "json",
            success: function (parsed_json) {
                var cities = [];
                console.log(parsed_json);
                for (i = 0; i < parsed_json['RESULTS'].length; i++) {
                    cities.push(parsed_json['RESULTS'][i]['name'])
                }
                $input.autocomplete('option', 'source', cities);
            }
        });
    });
});

Here's a Fiddle: http://jsfiddle.net/d8zxhq2b/

Upvotes: 1

Ricardo Pontual
Ricardo Pontual

Reputation: 3757

The "request" must be used with "source" object of autocomplete.

Here are an example:

$("#tags").autocomplete({
source: function (request, response) {
    $.get("http://autocomplete.wunderground.com/aq?", {
        query: request.term
    }, function (data) {
        response($.map(results, function (data) {
                    return {
                        label: data.name,
                        value: data.value
                    }
                }));
}});

Hope it helps.

Upvotes: 1

Related Questions