Select2 Ajax can't select options being pulled in from API - javascript

I'm trying to use the data in my API to populate a select input. I'm using Select2 and have everything working but am unable to select anything once results are found. I'll post my code below, I've been working on this for over 12 hours and can't find anything on the internet that works or even helps to get closer.
HTML:
<select id="school_input"></select>
Select2 Setup:
function formatResults (results) {
if (results.loading) return "Searching...";
var markup = "<div class='select2-result'>" + results.school_name + "</div>";
return markup;
}
$('#school_input').select2({
ajax: {
url: "http://services.url.com/services/globalopponentlookup.ashx",
dataType: 'jsonp',
delay: 250,
data: function (params) {
return {
school_name: params.term,
};
},
processResults: function (data, params) {
return {
results: data.schools,
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatResults
});
Example of data being pulled in from API:
jQuery31101273177236076506_1487863085363({
"schools": [
{
"school_search_keywords": "florida",
"website": "http://www.cf.edu/",
"school_id": "1514",
"school_name": "Central Florida Community College",
"school_website": "http://www.cf.edu/",
"school_location": "Ocala, FL ",
"school_mascot": "Patriots",
"school_logo_file": "CFpats.png",
"conference_id": "155",
"school_last_updated": "2/26/2014 9:23:51 AM",
"school_zip": "34474",
"school_ncaa_code": "0",
"school_abbrev": null,
"logo": "http://clients.url.com/files/logos/njcaa/CFpats.png",
"colors_id": null,
"url": null,
"safe_text_white": null,
"safe_text_black": null,
"primary_background": null,
"primary_text": null,
"secondary_background": null,
"secondary_text": null,
"client_id": null,
"created": null,
"deleted": null
},
{
"school_search_keywords": "florida",
"website": "http://www.easternflorida.edu/athletics/",
"school_id": "2521",
"school_name": "Eastern Florida State College",
"school_website": "http://www.easternflorida.edu/athletics/",
"school_location": "Cocoa, FL",
"school_mascot": "Titans",
"school_logo_file": "Eastern-Florida-State.png",
"conference_id": "155",
"school_last_updated": "1/19/2016 4:03:58 PM",
"school_zip": "32922",
"school_ncaa_code": null,
"school_abbrev": "EFSC",
"logo": "http://clients.url.com/files/logos/njcaa/Eastern-Florida-State.png",
"colors_id": null,
"url": null,
"safe_text_white": null,
"safe_text_black": null,
"primary_background": null,
"primary_text": null,
"secondary_background": null,
"secondary_text": null,
"client_id": null,
"created": null,
"deleted": null
}
]

You need to have Id value in the JSON in order to make it selectable. https://jsfiddle.net/adiioo7/Lqso63mw/2/
JS
function formatResults (results) {
if (results.loading) return "Searching...";
var markup = "<div class='select2-result'>" + results.school_name + "</div>";
return markup;
}
function formatRepoSelection (results) {
return results.school_name;
}
$('#school_input').select2({
ajax: {
url: "https://api.myjson.com/bins/15d345",
dataType: 'json',
delay: 250,
data: function (params) {
return {
school_name: params.term,
};
},
processResults: function (data, params) {
$(data.schools).each(function(){
this.id=this.school_id;
});
return {
results: data.schools,
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatResults,
templateSelection: formatRepoSelection
});

You need to return your markup from the formatResults() function :
function formatResults (results) {
if (results.loading) return "Searching...";
return "<div class='select2-result'>" + results.school_name + "</div>";
}
See the documentation

Related

How to use Kendo UI on Multi Select with Search using Post API

I have added Kendo UI on multi-select and use Post API to fetch the data on the basis of the search.
Here is the code in which I have tried to implement it.
var searchx = ""
var ds = new kendo.data.DataSource({
transport: {
read: {
url : "https://searchapi/list",
type: 'POST',
data: function (params) {
console.log("1");
var searchTerm = params.term && params.term != "" ? params.term : searchx;
var query = {
"txt": [
{
"txt: "Level4",
"values": [
"1819"
]
},
{
"txt": "Level3",
"values": []
},
{
"txt": "Level2",
"values": []
},
{
"txt": "Leve1",
"values": [
"278"
]
}
],
"xyz": [
{
"dt": "2022-04-24",
"field": "startDate"
},
{
"dt": "2022-05-24",
"field": "endDate"
}
],
"sorts": [],
"limit": 50,
"q": searchTerm
}
searchx = searchTerm;
console.log("2");
console.log(JSON.stringify(query));
return JSON.stringify(query);
//return Json(ds, JsonRequestBehavior.AllowGet);
},
contentType: 'application/json',
dataType: 'json',
success: function(data){
},
datatype: "json",
beforeSend: function (xhr) {
console.log('beforeSend');
xhr.setRequestHeader('Authorization','Bearer #Session.AuthToken~');
}
}
},
serverFiltering: true,
serverSorting: true,
placeholder: "Select One..."
});
$("#Tasks").kendoMultiSelect({
placeholder: "Select Tasks...",
filter: "contains",
autoBind: false,
dataValueField: "objectId",
dataTextField : "title",
dataSource : ds
});
Autocomplete / Typeahead search . I have created a Multi-select control by using kendo.The Multi-Select is not working Can anybody can help me with this

How to show data from get request in datatable?

I have been trying to show a json response of my rest application which is a rest application using tomcat server and i am using angular in the frontend and here is my controller
(function(){
'use strict';
angular.module('app')
.controller('wfCtrl', wfCtrl);
function wfCtrl($scope, $location, $http) {
var table=$('#example1').DataTable(
{
"bServerSide": true,
"fnServerData": function (sSource, aoData, fnCallback) {
var myData = JSON.stringify(aoData);
$.ajax({
"dataType": 'json',
"contentType" : "application/json;charset=utf-8",
"type": "GET",
"url": "http://localhost:8080/Spring4/data/lworkflows",
"data": null,
"success": fnCallback,
"error": function () {
console.log('have some problem');
}
});
},
"aoColumns": [
{ "mData": null }, // for User Detail
{ "mData": "code" },
{ "mData": "label" },
{ "mData": null },
{ "mData": null },
{ "mData": null },
{ "mData": null },
]
,
"order": [[ 1, "desc" ]]});
})();
the request url "http://localhost:8080/Spring4/data/lworkflows" returns a json data like this
{"WFLIGHT":{"code":"WFLIGHT","label":"Submit the deal"},"WFCOM":{"code":"WFCOM","label":"COM"},"WFPOCTBR":{"code":"WFPOCTBR","label":"Workflow Retail POC VW"},"WFRISK":{"code":"WFRISK","label":"RISQUES"},"WFDECF":{"code":"WFDECF","label":"DECIDEUR"},"WFETUDE":{"code":"WFETUDE","label":"ETUDE"},"WFADV":{"code":"WFADV","label":"ADV"},"TEST1":{"code":"TEST1","label":"Workflow Retail POC VW"},"WFCOM2":{"code":"WFCOM2","label":"ASSCOM"}}
the error i am getting is
Uncaught TypeError: Cannot read property 'length' of undefined
since my datatable cant read the data sent from the request
How can i resolve that ?
resolved after converting the response to an arrays
var output = wfs.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key];
});
here's the full working code
function wfCtrl($scope, $location, $http) {
$http({
method: 'GET',
url: 'http://10.10.216.201:8080/Spring4/data/lworkflows'
}).then(function successCallback(response) {
var wfs = response.data;
var output = wfs.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key];
});
});
console.log(output);
var table=$('#example1').DataTable(
{
"data":output,
"columns": [
{ "className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '' },
null,
null,
null,
null,
null,
{ "orderable": false }
]
,
"order": [[ 1, "desc" ]]});
}, function errorCallback(response) {
console.log("error");
});
}

jQuery UI autocomplete in AJAX/JSON

I have a problem with jQuery UI autocomplete that I'm trying to resolve with a lot of research and only resolved it partialy. I've managed to make it work at all with this code:
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}));
}
});
}
});
I'm working with open source API in JSON, here is an example:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 436,
"license_author": "Andrew Carothers",
"status": "1",
"description": "<p>1 Minute for each exercise</p>\n<ol>\n<li>Hold feet 6 inches off ground</li>\n<li>Crunches</li>\n<li>Side Crunches (L)</li>\n<li>Side Crunches (R)</li>\n<li>Heel Touches</li>\n<li>Plank Crunch</li>\n<li>Scissor Kicks</li>\n<li>Swim Kicks</li>\n<li>V Crunches</li>\n<li>Hold feet 6 in off ground</li>\n</ol>\n<p>Exercises can be substituted to vary workout</p>",
"name": "10 Min Abs",
"name_original": "10 Min Abs",
"creation_date": "2016-12-09",
"uuid": "3c5f6e1c-cb22-4a9f-a13e-d14afeb29175",
"license": 2,
"category": 10,
"language": 2,
"muscles": [],
"muscles_secondary": [],
"equipment": []
}
]
}
I want to get autocomplete suggestions with letters from "name" in JSON, but instead I've got whole JSON array, even with non-existing objects. I've already tried item.results[0].name, but everything I've got is TypeError: item.results is undefined. How to modify $.ajax to get "name" value of JSON object in autocomplete suggestions?
Thanks for any help.
does this work :
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data.results, function(index,item) {
return {
label: item.name,
value: item.name
}
}));
}
});
}
});

JQuery parsing only portion of JSON

Run into issue with parsing fairly complex JSON data.
What I am trying to achieve is parse the json data, extract address information and populate that in the typeahead drop down list.
JSON Data:
"{
"Version":"2.0.20",
"ResultCode":"XS02",
"ErrorString":"",
"Results":
[
{"Address":
{"AddressLine1":"300 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501","CountrySubdivisionCode ":"US-AK","AddressKey":"99501118273","SuiteName":"Apt","SuiteCount":3,"SuiteList":["","Apt A","Apt B"],"PlusFour":["1182","1182","1182"]}
},
{"Address":
{"AddressLine1":"240 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1150","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115040","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},
{"Address":
{"AddressLine1":"308 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1152","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115208","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},
{"Address":{"AddressLine1":"301 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1151","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115101","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},
]
}"
I only need to parse all the Addresses and extract AddressLine1 + City + State + PostalCode
JQuery:
$('#taquery').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'states',
displayKey: 'value',
source: function (query, process) {
return $.ajax({
url: "/addressLookup",
type: 'get',
data: { query: query },
dataType: 'json',
success: function (data) {
return typeof data == 'undefined' ? false : processResult(data);
}
});
}
});
var processResult = function (data) {
var addArray = $.makeArray(data.Results);
$.map(addArray, function (item, i) {
return (formatAddressJson(item.Address, i));
});
};
var formatAddressJson = function (addr, idx) {
var rtn;
rtn = {
fullAddress: addr.AddressLine1 + ', ' + addr.City + ', ' + addr.State + ', ' + addr.PostalCode,
addrLine1: addr.AddressLine1,
city: addr.City,
state: addr.State,
zip: addr.PostalCode.substring(0, 5),
idx: idx
};
return rtn;
}
Error:
jquery-1.10.2.min.js:4 Uncaught TypeError: Cannot use 'in' operator to search for '2548' in {"Version":"2.0.20","ResultCode":"XS02","ErrorString":"","Results":[{"Address":{"AddressLine1":"300 1/2 E Manor
var data = JSON.parse(response);
var addresses = data.results.reduce(function(agg, cur, idx) {
agg.push(formatAddress(cur.Address, idx)
return agg;
}, []);
function formatAddress(adr, idx) { //...your method }
// now you can loop over addresses array and access each.
addresses.forEach(function(addressObject) { console.log(addressObject) });
this code should make it work, you should use reduce method instead of map, and you do not need jquery to accomplish this.
EDIT
var JSON_FROM_SUCCESS_FUNCTION = {
"Version": "2.0.20",
"ResultCode": "XS02",
"ErrorString": "",
"Results": [{
"Address": { "AddressLine1": "300 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501118273", "SuiteName": "Apt", "SuiteCount": 3, "SuiteList": ["", "Apt A", "Apt B"], "PlusFour": ["1182", "1182", "1182"] }
}, {
"Address": { "AddressLine1": "240 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1150", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115040", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
}, {
"Address": { "AddressLine1": "308 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1152", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115208", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
}, {
"Address": { "AddressLine1": "301 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1151", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115101", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
}]
};
/*
$('#taquery').typeahead({
hint: true,
highlight: true,
minLength: 3
}, {
name: 'states',
displayKey: 'value',
source: function (query, process) {
return $.ajax({
url: "/addressLookup",
type: 'get',
data: { query: query },
dataType: 'json',
success: function (data) {
return typeof data == 'undefined' ? false : processResult(data);
}
});
}
});
*/
function processResult(data) {
return data.Results.reduce(function(agg, cur, idx) {
agg.push(formatAddress(cur.Address, idx));
return agg;
}, []);
};
function formatAddress(addr, idx) {
var fullAddress = addr.AddressLine1 + ', ' + addr.City + ', ' + addr.State + ', ' + addr.PostalCode;
return {
fullAddress: fullAddress,
addrLine1: addr.AddressLine1,
city: addr.City,
state: addr.State,
zip: addr.PostalCode.substring(0, 5),
idx: idx
};
}
var addresses = processResult(JSON_FROM_SUCCESS_FUNCTION);
// now you can loop over addresses array and access each.
addresses.forEach(function(addressObject) { console.log(addressObject) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Select2 AJAX Tags

I have the following JSON, that is retrieved via /tags:
[
{
"id": "CSS",
"text": "CSS"
},
{
"id": "HTML",
"text": "HTML"
},
{
"id": "JavaScript",
"text": "JavaScript"
},
{
"id": "jQuery",
"text": "jQuery"
},
{
"id": "MySQL",
"text": "MySQL"
},
{
"id": "PHP",
"text": "PHP"
}
]
I have an <input /> that is made to accept tags by using Select2:
<input name="Tags" id="Tags" value="PHP,HTML,jQuery" />
And I have attached Select2 this way:
$("#Tags").select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: true,
ajax: {
url: '/tags',
dataType: "json",
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});
Problems
When I load the page, the default values go off.
The Select2 fires a request to /tags, but it doesn't load the tags.
There are no errors in the console too. I am using Select2 3.5.2 from CDN. Where am I going wrong?
Well, I used this. Looks like a hack or work-around.
$("#Tags").select2({
tags: true,
multiple: true
});
$.getJSON("/tags", function (data) {
if (data.length > 0)
$("#Tags").select2({
tags: data,
multiple: true
});
});
Hope this helps for someone. I will keep this open till I get better suggestions.

Categories