How to use Select2 with JSON via Ajax request?

My Select2 3.4.5 does not work with JSON data.

Here is my HTML input field:

<input class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /> 

... and my javascript

 $(".itemSearch").select2({ placeholder: "Search for an Item", minimumInputLength: 2, ajax: { url: "/api/productSearch", dataType: 'json', quietMillis: 100, data: function (term, page) { return { option: term }; }, results: function (data, page) { var more = (page * 10) < data.total; return { results: data.itemName, more: more }; } }, formatResult: function (data, term) { return data; }, formatSelection: function (data) { return data; }, dropdownCssClass: "bigdrop", escapeMarkup: function (m) { return m; } }); 

I created an API with Laravel 4 that returns a value whenever I type anything in my text box.

Here's the result if I type "test" in my text box:

 [{"itemName":"Test item no. 1","id":5}, {"itemName":"Test item no. 2","id":6}, {"itemName":"Test item no. 3","id":7}, {"itemName":"Test item no. 4","id":8}, {"itemName":"Test item no. 5","id":9}, {"itemName":"Test item no. 6","id":10}, {"itemName":"Test item no. 7","id":11}] 

I cannot add the result to the Select2 drop-down list. I think formatSelection and formatResult are causing the problem because I don't know which parameter should be placed on it. I don’t know where to get parameters such as the container, object and request, and the values ​​that it should return, or is my JSON response incorrect?

+77
json javascript laravel jquery-select2
Jan 04
source share
8 answers

Here is an example

 $("#profiles-thread").select2({ minimumInputLength: 2, tags: [], ajax: { url: URL, dataType: 'json', type: "GET", quietMillis: 50, data: function (term) { return { term: term }; }, results: function (data) { return { results: $.map(data, function (item) { return { text: item.completeName, slug: item.slug, id: item.id } }) }; } } }); 

It's pretty easy

+95
Feb 06 '14 at 11:52
source share

for select2 v4.0.0 is slightly different

 $(".itemSearch").select2({ tags: true, multiple: true, tokenSeparators: [',', ' '], minimumInputLength: 2, minimumResultsForSearch: 10, ajax: { url: URL, dataType: "json", type: "GET", data: function (params) { var queryParameters = { term: params.term } return queryParameters; }, processResults: function (data) { return { results: $.map(data, function (item) { return { text: item.tag_value, id: item.tag_id } }) }; } } }); 
+98
Sep 18 '15 at 14:19
source share

In version 4.0.2, it is slightly different. Just in processResults and in result :

  processResults: function (data) { return { results: $.map(data.items, function (item) { return { text: item.tag_value, id: item.tag_id } }) }; } 

You should add data.items to result . items - Json name:

 { "items": [ {"id": 1,"name": "Tetris","full_name": "s9xie/hed"}, {"id": 2,"name": "Tetrisf","full_name": "s9xie/hed"} ] } 
+15
May 6 '16 at 10:29 PM
source share

This is how I fixed my problem, I get the data in the data variable and using the solutions described above, I got the error could not load results . I had to analyze the results differently in processResults.

 searchBar.select2({ ajax: { url: "/search/live/results/", dataType: 'json', headers : {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, delay: 250, type: 'GET', data: function (params) { return { q: params.term, // search term }; }, processResults: function (data) { var arr = [] $.each(data, function (index, value) { arr.push({ id: index, text: value }) }) return { results: arr }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, minimumInputLength: 1 }); 
+6
May 17 '17 at 20:12
source share

Here I will give my example, which contains β†’ Country flag, City, State, Country.

Here is my conclusion.

enter image description here

Attach these two JS CDNs or links.

 <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script> 

Js script

 //for apend flag of country. function formatState (state) { console.log(state); if (!state.id) { return state.text; } var baseUrl = "admin/images/flags"; var $state = $( '<span><img src="'+baseUrl+ '/' + state.contryflage.toLowerCase() + '.png" class="img-flag" /> ' +state.text+ '</span>' ); return $state; }; $(function(){ $("#itemSearch").select2({ minimumInputLength: 2, templateResult: formatState, //this is for append country flag. ajax: { url: URL, dataType: 'json', type: "POST", data: function (term) { return { term: term }; }, processResults: function (data) { return { results: $.map(data, function (item) { return { text: item.name+', '+item.state.name+', '+item.state.coutry.name, id: item.id, contryflage:item.state.coutry.sortname } }) }; } } }); 

Expected JSON response.

 [ { "id":7570, "name":"Brussels", "state":{ "name":"Brabant", "coutry":{ "sortname":"BE", "name":"Belgium", } } }, { "id":7575, "name":"Brussels", "state":{ "name":"Brabant Wallon", "coutry":{ "sortname":"BE", "name":"Belgium", } } }, { "id":7578, "name":"Brussel", "state":{ "name":"Brussel", "coutry":{ "sortname":"BE", "name":"Belgium", } } }, ] 
+3
Sep 05 '19 at 7:31
source share

Problems may be caused by incorrect display. Are you sure your result is set to "data"? In my example, the backend code returns the results under the "items" key, so the display should look like this:

 results: $.map(data.items, function (item) { .... } 

and not:

  results: $.map(data, function (item) { .... } 
+1
Jan 28 '17 at 17:04 on
source share

My ajax will never be fired until I wrap it all in

setTimeout(function(){ .... }, 3000);

I used it in a mounted Vue partition. it takes more time.

+1
Mar 18 '18 at 7:45
source share

If the ajax request does not start, check the select2 class in the select element. Removing the select2 class will solve this problem.

0
Sep 09 '18 at 5:34
source share



All Articles