Stuart Brown Stuart Brown - 3 years ago 204
Javascript Question

Unable to load remote data son into select2

I've been trying for many hours to get a remote JSON file to import into a select2 input as options, but without any success.

I am using version 3.5.3 of Select2 which is loaded into Drupal by a module, so I'm sort of stuck with that for the time being.

I should say that I have very little experience with javascript and JSON, although I have spent several hours going through various select2 tutorials, and whilst the script changes the input to a select2 field, whatever I type in the search just returns an error on the field, "loading failed".

There are no messages in the console, so I have no idea where I'm going wrong. I suspect it may be the JSON file, for which I am using a manually created JSON file which I have simply uploaded to a web server, called test.json. Here is the code from that:

[

{
"entry_id": "45117",
"url": "http://www.example.com",
"title": "Title text 1",
"count": "2",

},

{
"entry_id": "45096",
"url": "http://www.example.com",
"title": "Title text 2",
"count": "5",
}
]


I am wanting to have the "title" field displayed in the select2 dropdown and the "entry_id" field stored as the value when the form is submitted. I believe this is how select2 works, but with the field names of "id" and "text", so I need my JS to map my fields.

I can't change the JSON output format, as the real world file I will be using is via a third party (which I don't have access to yet hence the test file) and won't be changeable.

Here's my JS:

$("#myfieldid").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: "http://mydomain.uk/test.json",
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.entry_id
}
})
};
}
}
});


And here's my html:

<input type="text" id="myfieldid" name="myfieldname" value="" size="60" maxlength="255" tabindex="-1" style="display: none;">


Apologies for the lengthy post, I really am stuck here, I fully expected everything to be working from the code I had, so my thoughts are that it's the JSON file, ether the format or the way it's been generated that is causing the problem.

Answer Source

I looked at your code and saw a couple of issues.

1) You need to have a <select> element instead of <input> in your html.

2) The example JSON you provided has some extra commas (after the count field). When testing, Chrome refused to load this data due to these commas. Are you sure your actual data also has these commas? If so there may be workarounds, but for now I will be assuming your real JSON is actually correctly formatted.

In addition, I would load your JSON data in a variable and then pass this to select2 instead of having select2 do the ajax calls. Otherwise, the library will query the server for the json file on each keystroke in the search field as this is really meant for server-side searching/filtering.

The result could look something like this:

<!-- various HTML elements -->
<select id="myfieldid" name="myfieldname" tabindex="-1">
<!-- various HTML elements -->

<script>
$(document).ready(function() {
  $.ajax({
    async: true,
    url: "data.json",
    dataType: "json",
    error: function (jqXhr, status, error) {
      alert("Error loading data!");
    },
    success: function (data) {
      data = $.map(data, function (item) {
        return {
          text: item.title,
          id: item.entry_id
        };
      });
      $("#myfieldid").select2({
        minimumInputLength: 2,
        data: data
      });
    }
  });
});
</script>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download