oligan
oligan

Reputation: 634

jquery autocomplete with an ajax call to generate the array

i'm trying to do a jquery ui autocomplete with some countries i get from db with an ajax call

I'm struggling on how to pass my table of values to the autocomplete

 $( document ).ready(function() {

    $.ajax({
        url:Routing.generate('e_veilleur_user_register_countries_autocomplete'),
        type:"get",
        dataType: 'json',
        data: 'test=cool',
        async: true,
        cache: true,
        success: function(data){
            var availableTags = data;
        }
    });

    $( "#fos_user_registration_form_pays" ).autocomplete({
        source: availableTags
    });
  });

The result of my ajax call is

[{"countryName":"United States"},
 {"countryName":"Canada"},
 {"countryName":"Afghanistan"},
 {"countryName":"Albania"},
 {"countryName":"Algeria"}

Error given : availableTags is not defined

Upvotes: 2

Views: 2592

Answers (1)

MinusFour
MinusFour

Reputation: 14423

You could use a custom function for source, which uses AJAX instead. So you don't have to synch with an AJAX call outside the scope.

$( "#fos_user_registration_form_pays" ).autocomplete({
    source: function(request, response) {
       $.ajax({
       url:Routing.generate('e_veilleur_user_register_countries_autocomplete'),
       type:"get",
       dataType: 'json',
       data: 'test=cool',
       async: true,
       cache: true,
       success: function(data){
          response(data);
       }
     });
    }
});

jQuery UI Autocomplete Source

Edit

I didn't see the comment, up until now. Answering that specific comment, you can just call autocomplete from within the AJAX.

$.ajax({
    url:Routing.generate('e_veilleur_user_register_countries_autocomplete'),
    type:"get",
    dataType: 'json',
    data: 'test=cool',
    async: true,
    cache: true,
    success: function(data){
        $( "#fos_user_registration_form_pays" ).autocomplete({
        source: data
        });
    }
});

Upvotes: 5

Related Questions