Select2 "TypeError: a is undefined" error

I have this code to create a Select2 element from an input field:

 var codigo_arancelario = $codigo_arancelario.val(); $codigo_arancelario.select2({ placeholder: "Seleccione un estado", ajax: { dataType: 'json', url: function () { return Routing.generate('obtenerCodigoArancelario'); }, data: function (codigo_arancelario) { return { filtro: codigo_arancelario } }, results: function (data) { var myResults = []; $.each(data.entities, function (index, item) { myResults.push({ 'id': item.id, 'nombre': item.nombre }); }); return { results: myResults }; } }, formatNoResults: function () { return "No se encontró el código"; }, formatAjaxError: function () { return "No hay conexión con el servidor"; } }); 

But anytime when I try to use it, I get this error on the Firebug console:

TypeError: a undefined

I checked the response headers and I got the Content-Type application/json , and I also check the request headers since I use Symfony2 on the server side and it sends X-Requested-With XMLHttpRequest . The Symfony2 function returns JSON as follows:

 { "valid":false, "entities":[ { "id":101, "codigo":"4545", "descripcion":null }, { "id":102, "codigo":"45455", "descripcion":"gfhgfhfghfgh" }, { "id":103, "codigo":"45457", "descripcion":"etert" } ] } 

Where is the error in my code?

+5
source share
2 answers

Select2 expects [{text="john doe",id="1"},{text="jane doe",id="2"}]

so you need to change 'nombre': item.nombre to 'text': item.nombre it should look like this:

  myResults.push({ 'id': item.id, 'text': item.nombre }); 
+5
source

Perhaps your data is erroneous:
data Type: PlainObject or String or Array Data to send to the server. It is converted to a query string if it is not already a string. It is added to the URL for GET requests. See the processData parameter to prevent this automatic processing. The object must be key / value pairs. If the value is an array, jQuery serializes multiple values ​​with the same key based on the value of the traditional setting (described below).

see jquery for ajax

-1
source

Source: https://habr.com/ru/post/1205248/


All Articles