2

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

2
  • AJAX is asynchronous, you're using availableTags before the AJAX completes. jQuery Autocomplete allows you to specify an AJAX URL in the source: option, use that. Commented Nov 7, 2014 at 17:03
  • indeed ! but puting an url will call the ajax everytime i type aletter, right ? i'd like to load the whole array at the beginning, is it possible? or i am wrong and putting url preloads the array Commented Nov 7, 2014 at 17:06

1 Answer 1

5

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
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.