How to load JSON data to use it with select2 plugin
Asked Answered
W

2

16

I want to use select2 plugin for my project. I followed this example, but it doesn't work for me.

JSON output :

[
    {"ime":"BioPlex TM"},
    {"ime":"Aegis sym agrilla"},
    {"ime":"Aegis sym irriga"},
    {"ime":"Aegis sym microgranulo"},
    {"ime":"Aegis sym pastiglia"},
    {"ime":"Agroblen 15816+3MgO"},
    {"ime":"Agroblen 18816+3MgO"},
    {"ime":"Agrobor 15 HU"},
    {"ime":"Agrocal (Ca + Mg)"},
    {"ime":"Agrocal (Ca)"},
    {"ime":"Agrogold"},
    {"ime":"Agroleaf Power 12525+ME"},
    {"ime":"Agroleaf Power 151031+ME"},
    {"ime":"Agroleaf Power 202020+ME"},
    {"ime":"Agroleaf Power 311111+ME"},
    {"ime":"Agroleaf Power Ca"},
    {"ime":"Agrolution 14714+14 CaO+ME"},
    {"ime":"Agrovapno dolomitno"},
    {"ime":"Agrovit HSF"},
    {"ime":"Agrovit P"},
    {"ime":"Agrozin 32 T"},
    {"ime":"Albatros Hydro"},
    {"ime":"Albatros Sprint"},
    {"ime":"Albatros Standard"},
    {"ime":"Albatros Universal"},
    {"ime":"Algaren"},
    {"ime":"AlgoVital ? Plus"},
    {"ime":"Amalgerol PREMIUM"},
    {"ime":"Amcolon \/ Novalon"},
    {"ime":"Amcopaste"},
    {"ime":"Aminosprint N8"},
    {"ime":"AminoVital"},
    {"ime":"Ammonium nitrate 33.5%"},
    {"ime":"Ammonium nitrate with calcium sulfate"},
    {"ime":"Ammonium sulfate"}
]

Script :

function formatDjubrivo(data) {
    return data;
}
function formatDjubrivo1(data) {
    return data.ime;

$( "#inputs" ).change(function() {
    console.log('prolazi klik');
    var t = $( this ).val();
    console.log(t);
    if (t=='djubrivo') {
       console.log('prolazi klik if');
       $('#stavka').select2({
          ajax: {
             dataType : "json",
             url      : "djubrivo.php",
             results  : function (data) {
                 return {results: data};
             }
          },
          formatResult : formatDjubrivo
       });
    }else {
       console.log('nije djubrivo');
    }
});

HTML :

<div class="col-md-2" style="padding-right:0px;">
    Vrsta Inputa
    <select id="inputs" name="inputs" class="form-control js-example-responsive">
        <option value="djubrivo">djubrivo</option>
        <option value="pesticidi">pesticidi</option>
        <option value="kultura">kultura</option>
        <option value="voda">voda</option>
    </select>
</div>

<div class="col-md-2" style="padding-right:0px;">
    Stavka
    <input id="stavka" name="stavka" class="form-control js-example-responsive">
</div>

This is the result when I test my code using console.log:

Select2: The AJAX results did not return an array in the results key of the response.

Where did I made mistake?

Wet answered 5/2, 2015 at 22:14 Comment(3)
if you browse djubrivo.php you get the json array?Gap
yes, offcource I get this JSON: [{"ime":"BioPlex TM"},{"ime":"Aegis sym agrilla"},{"ime":"Aegis sym irriga"},{"ime":"Aegis sym microgranulo"},{"ime":"Aegis sym pastiglia"},{"ime":"Agroblen 15816+3MgO"},{"ime":"Agroblen 18816+3MgO"},{"ime":"Agrobor 15 HU"},{"ime":"Agrocal (Ca + Mg)"},{"ime":"Agrocal (Ca)"},{"ime":"Agrogold"},{"ime":"Agroleaf Power 12525+ME"},{"ime":"Agroleaf Power 151031+ME"},{"ime":"Agroleaf Power 202020+ME"},{"ime":"Agroleaf Power 311111+ME"} etc. ... ...Wet
something was changed from version 3.4.2 becouse there I can load JSON at the same way, but now when I try 4.0.0 version this dont work... And my json array output is fine... the same as on the docsWet
D
60

It appears you are using Select2 4.0, both from the link you provide to the examples and from the error message you are receiving. Your code, however, is written for previous versions of Select2.

If you want to continue to use Select2 4.0:

(1) Change the results ajax option to processResults.

(2) Change the processResults function so the results property of the object it returns is an array of objects, where each object has an id and a text property. One way to do this is to use the $.map() function to create a new array from the one that is returned by the ajax call.

processResults: function (data) {
    return {
        results: $.map(data, function(obj) {
            return { id: obj.ime, text: obj.ime };
        })
    };
}

You can also get rid of the formatResult option.

(3) Use a <select> element, instead of an <input> element.

<select id="stavka" name="stavka" class="form-control js-example-responsive"></select>

jsfiddle

Dogmatic answered 5/2, 2015 at 22:29 Comment(6)
thanks now work, but WHY I CANT USE SEARCH FIELD when I click on select2 field ? I cant type anythingWet
@dertdetg - Do you mean in the jsfiddle? You can type in the search field in the jsfiddle, but its value is not being used.Dogmatic
no, at my project localhost, I cant use serach field into select2... why? Maybe becouse its into modal bootstrap window ???Wet
@dertdetg - I don't see anything in the code in your question that would prevent you from typing in the search field. You aren't passing the value of the search field in your ajax request though, so the search field is not being used in your code.Dogmatic
THANKS FOR HELP! ok, how I can do that? does select2 have build in function for that?Wet
@dertdetg - You have to pass the search term in your ajax request, and then your server code that handles that request needs to use the search term to limit the results that are returned. See the "Loading remote data" section on the examples page you linked to. The ajax data option is used to pass the search term as a request parameter named q. Of course, you can name the parameter whatever you want.Dogmatic
H
5

try this :

$.getJSON("djubrivo.php", function (json) {
      $("#inputs").select2({
         data: json,
         width: "180px"
      });
 });

example json :

    {
      results:{
        {id:0,text:"enhancement"},
        {id:1,text:"bug"},
        {id:2,text:"duplicate"},
        {id:3,text:"invalid"},
        {id:4,text:"wontfix"}
      }
    }
Havre answered 5/6, 2015 at 0:30 Comment(2)
This is not what the OP asked. You are making one request and caching the results. If a new djubrivo is created after your GET request, it will not be present in the select.Fitch
yes but it is helpful if ajax to load complete list.. not while typing and code is working fine for thatOdontoblast

© 2022 - 2024 — McMap. All rights reserved.