select2 ajax shows results but can't select
Asked Answered
W

4

8

I'm using select2 plugin with remote ajax data. I can see the results in the dropdown but can't select them. I want the results to be selectable and placed into the field after selection. I think the problem is with passing the id, I don't know how to pass it correctly.. Any ideas?

my json for ?tag_word=for ...there is no id

results: [{text: "fort"}, {text: "food"}]

Here the code:

    <select class="js-data-example-ajax" style="width:100%">
      <option selected="selected">asdasd</option>
    </select>

    <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
    <script type="text/javascript" src="{% static 'js/select2.js' %}"></script>
    <script >
    $(document).ready(function(){
    $('.js-data-example-ajax').select2({
    minimumInputLength: 2,
    multiple:true,
    delay: 250,
    cache: true,
    ajax: {
      url: '/tags/search/autocomplete/',
      dataType: 'json',
      data: function (parms, page) { return { tag_word: parms.term }; },
    },
  });
});  
    </script>

here is the server code:

def autocomplete(request):
s = SearchQuerySet(using='autocomplete')
sqs = s.autocomplete(content_auto=request.GET.get('tag_word'))[:5]
suggestions = [  {'text':result.tag_word,
                    'id':result.tag_word,} for result in sqs]
the_data = json.dumps({
    'results': suggestions
})
return HttpResponse(the_data, content_type='application/json')
Weathersby answered 24/7, 2015 at 17:12 Comment(1)
you need to use the success: of $.ajaxPromulgate
O
3

Its a quick hack. Not sure how you could get along with select2 documentaion. But the following code worked with me in my localhost.

$(document).ready(function(){
         $.get("json/select.json",function(data){ //specify your url for json call inside the quotes.
             for(var i = 0; i < data.length; i++){
                 data[i]={id:i,text:data[i].text}
             }
            $(".js-data-example-ajax").select2({
                    minimumInputLength: 2,
                    multiple:true,
                    delay: 250,
                    data: data   
            })

    });
}
Obstructionist answered 27/7, 2015 at 7:39 Comment(3)
If I use the above code I get the error: 127.0.0.1:8000/tags/search/autocomplete 500 (INTERNAL SERVER ERROR)Weathersby
Ok i did it on the server side since I can't find out the solution on client side.. I just added same property 'tag_word' also for id and not only for text.. now is workingWeathersby
Pick the right answer so it will be helpful for other who search on the same base.Obstructionist
L
9

To select an option each and every result need to have a unique id. Therefore you can add id using following code(processResults).

$('.js-data-example-ajax').select2({
    minimumInputLength: 2,
    multiple:true,
    delay: 250,
    cache: true,
    ajax: {
        url: '/tags/search/autocomplete/',
        dataType: 'json',
        data: function (parms, page) { return { tag_word: parms.term }; },
        processResults: function (data) {
                    data.results.forEach(function (entry, index) {
                        entry.id = ''+index; // Better if you can assign a unique value for every entry, something like UUID
                    });

                    return data;
                },
                cache: true
    },
});
Limonene answered 4/8, 2016 at 18:57 Comment(0)
O
3

Its a quick hack. Not sure how you could get along with select2 documentaion. But the following code worked with me in my localhost.

$(document).ready(function(){
         $.get("json/select.json",function(data){ //specify your url for json call inside the quotes.
             for(var i = 0; i < data.length; i++){
                 data[i]={id:i,text:data[i].text}
             }
            $(".js-data-example-ajax").select2({
                    minimumInputLength: 2,
                    multiple:true,
                    delay: 250,
                    data: data   
            })

    });
}
Obstructionist answered 27/7, 2015 at 7:39 Comment(3)
If I use the above code I get the error: 127.0.0.1:8000/tags/search/autocomplete 500 (INTERNAL SERVER ERROR)Weathersby
Ok i did it on the server side since I can't find out the solution on client side.. I just added same property 'tag_word' also for id and not only for text.. now is workingWeathersby
Pick the right answer so it will be helpful for other who search on the same base.Obstructionist
O
2

Its because you got all id's null. change to numbers. Click on the get selected button to see the ids only will be passed.

var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];

$(document).ready(function(){

    $('.js-data-example-ajax').select2({
    minimumInputLength: 2,
    multiple:true,
    delay: 250,
    data: data


  });
});

$(".checkoutput").click(function(){
console.log($('.js-data-example-ajax').val());
})

Here is the JSFIDDLE

Obstructionist answered 24/7, 2015 at 21:22 Comment(12)
my id's are null that's the problem you are correct. Can you please explain how do I pass only id values to json? I tried your suggestion but can't make it work.Weathersby
//how do I pass only id values to json// Couldnt get your point. You need to keep id and text. And you need to give unique value for each id.Obstructionist
yes i need both id and text but I already get the text.. I miss the id and I can't figure out how to give unique value to each id.. my current results: [{text: "fort"}, {text: "food"}].. there is no id. How do I add unique id to my results?Weathersby
[{id:0, text: "fort"}, {id:1,text: "food"}]. Did i get your question?Obstructionist
yes this should be the final result but I load json with ajax. My question is how to add id unique values when I use remote data loading and I don't have an array of values..Weathersby
If you have not created the json, then you need to ask the backend guys to create the similar json for you. The quick way to test your front-end code is create a json file and call that file instead of url and check. If it works fine then you can ask your backend guys to create similar json for you. Hope i was clear.Obstructionist
I have the backend and it's calling only tag_word which is a charfield. I could call also the pk and use that as id but I'm sure there are other ways to add id's dynamically in jquery. This link javascriptgraduate.com/question/… has the exact same issue that I'm facing and I tried also his method but can't add the id to my results. As i said my backend json is created but returns only "text" not also the "id". That is the reason why i can see the results but can't select them...Weathersby
you are using jquery or javasciptObstructionist
for this case I'm using jquery select2 (loading remote data)Weathersby
see this jsfiddle. look into the console. it will add id to your json value. jsfiddle.net/alaksandarjesus/084wbz0gObstructionist
can you please show me exactly where should I insert your code?Weathersby
@gibberish is right. you need to append the code after success function.Obstructionist
F
0

Further to your final question on Alaksandar's answer, try adding his code like this:

$('.js-data-example-ajax').select2({
    minimumInputLength: 2,
    multiple:true,
    delay: 250,
    cache: true,
    ajax: {
        url: '/tags/search/autocomplete/',
        dataType: 'json',
        data: function (parms, page) { return { tag_word: parms.term }; },
        success: function(results){
            for(var i = 0; i < results.length; i++){
                results[i] = {id:i,text:results[i].text}
            }
        }
    },
});

I haven't tested any of this. So, if it works, please accept Aleksandar's answer as correct, not this one.

Frontier answered 26/7, 2015 at 20:2 Comment(2)
thanks for your suggestions but I still can't select the items and the console is showing: results: [{text: "fort"}, {text: "food"}]...without id valueWeathersby
what is your parms.term outputObstructionist

© 2022 - 2024 — McMap. All rights reserved.