Select2 Ajax results could not be loaded - ajax

Whenever I try to search for result in my select2 ajax searchbar I receive the following message:
'The results could not be loaded'
Html:
<select class="js-data-example-ajax form-control" multiple="multiple"></select>
Javascript:
$('select').each(function(idx, ele) {
$(ele).select2({
theme: 'bootstrap4',
placeholder: ele.getAttribute('placeholder'),
ajax: {
url: '/product/api/search',
dataType: 'json' },
type: 'GET',
});
});
I think that my Ajax settings are wrong could you assist?

Your code should look like this. No GET method needed.
$('select').each(function(idx, ele) {
$(ele).select2({
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json'
// Additional AJAX parameters
}
}
});
Also your problem might be in your source json format because select2 need own format with results.
In order to accomplish this, Select2 expects a very specific data
format. This format consists of a JSON object containing an array of
objects keyed by the results key.
{
"results": [
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2"
}
}
Also you can use processResults or transform data into certain format.

Related

How to parse my JSON data to String in KENDO GRID?

how can i format this object Object to its actual values ?
I want this json object to display its actual values in a specific kendo grid column .
Can someone please help me and teach me how to do it ?
This is the image of the kendo grid with the result ,
While here is the code that I am using in my view .
Can please someone help .
contact : new kendo.data.DataSource({
transport:{
read:{
type: "GET",
url:"reservation/list",
dataType:"json",
contentType: "application/json; chartset=utf-8"
},
update: {
url: "contacts/update",
dataType: "json",
type: "POST"
},
destroy: {
url: "contacts/destroy",
dataType: "json",
type:"POST"
},
create: {
url: "contacts/store",
dataType: "json",
type:"POST"
}
},
schema:{
model:{
id:"id",
fields:{
Purpose:
{
type:"string",
validation:{required:true}
},
RoomID:
{
from: "RoomID.room_name",
type: "string"
},
Equipments:
{
from: "Equipments",
type: "string"
},
start:
{
type:"date",
validation:{required:true}
},
end:
{
type:"date",
validation:{required:true}
},
}
}
},
pageSize:10
}),
init : function(e){
$("#grid").kendoGrid({
dataSource: this.contact,
selectable: true,
height:600,
editable: "popup",
filterable: true,
sortable: {
mode: "multiple",
allowUnsort: true,
showIndexes: true
},
toolbar: ["search"],
columns: [
{
field: "Purpose",
title:"Purpose"
},
{
field: "RoomID",
title:"Room",
},
{
field: "Equipments",
title:"Equipments",
},
{
field: "start",
title:"Start",
//template: '#= kendo.toString(kendo.parseDate(start), "MM/dd/yyyy HH:mm:ss")#'
format: "{0:MMM dd,yyyy hh:mm tt}",
parseFormats: ["yyyy-MM-dd'T'HH:mm.zz"]
},
{
field: "end",
title:"End",
//template: '#= kendo.toString(kendo.parseDate(end), "MM/dd/yyyy HH:mm:ss")#'
format: "{0:MMM dd,yyyy hh:mm tt}",
parseFormats: ["yyyy-MM-dd'T'HH:mm.zz"]
},
{
command: ["edit", "destroy"],
title: " ",
width: "250px"
}
],
pageable:{
pageSize:10,
refresh:true,
buttonCount:5,
messages:{
display:"{0}-{1}of{2}"
}
}
});
},
});
kendo.bind($("#whole"),model);
model.init();
Hopefully this will help you out with templating out the results.
https://dojo.telerik.com/ICOceLUj
In the example above I have created a custom column that takes the incoming row object and then parsed the name of the item and the category object into a single template.
To achieve this I have added the template property and used a function with an external template script to handle the manipulation. I personally find this easier to manage than trying to inline a complex client template (especially if you have logic involved)
So this is how we set it up initially:
{ title: "custom template", template:"#=customTemplate(data)#" }
obviously you will change it to the property you need to look at in your model.
then the function is a couple of lines of code:
function customTemplate(data){
var template = kendo.template($('#customTemplate').html());
var result = template(data);
return result;
}
so this takes the customTemplate template i have created for this and renders it as html and then it will apply the data where appropriate. The template looks like this:
<script id="customTemplate" type="text/x-kendo-template">
<div>
<h5> #:data.ProductName#</h5>
<h4>#: JSON.stringify(data.Category, null, 4) #</h4>
</div>
</script>
You can then customize this template to how you need it to look for your specific needs. You can then either create a source template for the items and then map the values back as single string or have the logic for this in the template. Which ever is most sensible in your case.
For more info on templating please look at this link:
https://docs.telerik.com/kendo-ui/framework/templates/overview
You can use kendo.stringify in your column template.
Example:
kendo.stringify(YourProperty)

Kendo DropDownList Preserve Whitespace in Option

I am using Kendo UI for JQuery/AngularJS.
I have the following <select> control defined:
<select
kendo-drop-down-list
k-options="myOptions">
</select>
I have a datasource returning JSON with VALUE representing the value for an <option>, and TEXT representing the label for the option.
Unfortunately, the VALUE returns with leading spaces, meant to represent a hierarchy:
[
{VALUE: 1, TEXT: 'Accounting'},
{VALUE: 2, TEXT: ' Accounts Payable'},
{VALUE: 3, TEXT: ' Accounts Receivable'}
]
This should correspond to an group of options like the following:
<option value="1">Accounting</option>
<option value="2"> Accounts Payable</option>
<option value="3"> Accounts Receivable</option>
Below is my definition of options:
$scope.myOptions = {
autoWidth: true,
autoBind: false,
dataTextField: 'TEXT',
dataValueField: 'VALUE',
dataSource: {
transport: {
read: {
url: urlToREST,
dataType: 'json',
type: 'POST',
contentType: "application/json"
},
// needed to send params as JSON
parameterMap: function (data, type) {
const req = {
"QUERY_ID": $scope.queryId
};
return JSON.stringify(req);
}
},
schema: {
type: "json",
data: "resultData"
}
}
};
I need to represent multiple levels of a hierarchy in the options. I felt the best way would be to use Javascript to dynamically create a <pre> section, but it's not working.
Can anyone help me?
I ended up dynamically computing the amount of whitespace required to represent the hierarchy, then adding for each space (the number of spaces is a parameter returned by the remote service call):
function indent(spaceCount) {
return ' '.repeat(spaceCount);
}
$scope.options = {
dataTextField: 'TEXT',
dataValueField: 'VALUE',
template: function(dataItem) {
return kendo.template(indent(dataItem.spaces -1) *4) + '#: DESCRIPTION #')(dataItem);
},
dataSource: {
transport: {
read: {
// read definition
},
// needed to send JSON parameters to the query
parameterMap: function(data, type) {
const req = {
'QUERY_ID': $scope.queryId
};
return JSON.stringify(req);
}
},
schema: {
type: 'json',
data: 'resultData'
}
}
};
The indent function could have been done inline. This could also probably have been refactored into an AngularJS service as well.
I ended up using the template function and specified a table within the template
Which allows me to specify width for each row
#(Html.Kendo().ComboBoxFor(model => model.PersonId)
.DataTextField("FullName")
.DataValueField("Id")
.Value("")
.Filter(FilterType.Contains)
.MinLength(2)
.AutoBind(true)
.Template("<table><tr><td width='200px'>#: data.FullName #</td><td width='100px'> - #: data.EmpId #</td></tr></table>")
.DataSource(s =>

Datatables: Button for Showing Photo for Each Filename

I am very new to Datatables and this might be simple, but surely I am missing something. I am trying to create a button column that uses the filename of each row and uses it to make an ajax call to display a picture on click. What I get wrong is that, every button of the column displays the same image, and not the image of the filename for each row. Here is the code:
$.ajax ({
url: "http:// ...... /Services/DBPrintDatatable?customer_id=" + projectid,
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"aaSorting": [],
"columns": [
{ "data": "upload_date" },
{ "data": "filename" },
{ "data": "uploader" },
{ "data": "upload_place" },
{ "data": "is_ok" },
{ "data": "custom_verdict" },
{
data: { "data": "filename" },
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename='+ { 'data': 'filename' }>Show</a>";
}
},
] ,
});
Thank you in advance!
If the image url required is like
http://......./Services/DBShowImage?filename=filenameFromData
Then you should generate it first inside the render like below code
href='http://......./Services/DBShowImage?filename="+ row.filename+"';
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename="+ row.filename+"'>Show</a>";
}

Kendo UI ListView that consumes object with array

How can I get my ListView to loop through object property timetableRecords. I'm googling around but can't find way to do it.
Example of data (swagger response model schema):
{
"from": {
"name": "string"
},
"to": {
"name": "string"
},
"price": 0,
"date": "2016-07-25T11:52:52.674Z",
"timetableRecords": [
{
"departure": "2016-07-25T11:52:52.675Z",
"arrival": "2016-07-25T11:52:52.675Z"
}
],
"fetchedOn": "2016-07-25T11:52:52.675Z"
}
HTML:
<div id="timetableRecords"></div>
<script type="text/x-kendo-template" id="template">
<div class="timetable-record">
<p>#:departure#</p>
<p>#:arrival#</p>
</div>
</script>
JavaScript:
$('#timetableRecords').kendoListView({
template: kendo.template($("#template").html()),
dataSource: {
transport: {
read: {
type: 'GET',
url: 'api/timetable?from=station_name1&to=station_name2',
dataType: 'json'
}
}
}
});
So its been awhile since you posted this, but I have a solution for you (doubtful you will still need it).
The schema.parse() event can help you:
Executed before the server response is used. Use it to preprocess or parse the server response.
Here is your updated Datasource is below:
dataSource: {
transport: {
read: {
type: 'GET',
url: 'api/timetable?from=station_name1&to=station_name2',
dataType: 'json'
}
},
schema:
parse: fucntion(e) {
return e.timetableRecords
}
}
This way your DataSource is processing a list of 'timetableRecords', and your template would be valid.
Good luck,
Grant

Ajax Post Create Features Google Maps Engine API

So here is my code, i've already made the oauth handshake, and that has given me the authentication token which i'm including in my header. I am simply trying to batch insert some features into an existing table. I keep getting a 400 "parseError" - This API does not support parsing form-encoded input.
Here's some of my code. I have no idea where i'm derping any ideas.
$(document).ready(function(){
$('.pickTrip').bind('click', function(){
var pointData = {
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-87.397980,
44.795067
]
},
"properties": {
"gx_id": "1242342",
"name": "Jimmy Choo",
"phone": "(920)555-4242",
"email": "jchoo#aol.com",
"vehicle": "mazda, b2300, 1994"
}
}
]
};
console.log(pointData);
var url = "https://www.googleapis.com/mapsengine/v1/tables/{table id}/features/batchInsert";
jQuery.ajax({
type: "POST",
url: url,
data: pointData,
dataType: 'application/json',
headers: {
'Authorization': 'Bearer ' + authResult.access_token
},
success: function(response) {
// Log the details of the Map.
console.log(response);
},
error: function(response) {
response = JSON.parse(response.responseText);
console.log("Error: ", response);
}
});
});
});
jQuery takes the object provided in the 'data' parameter and turns the key/value pairs into an encoded query string. You will want to send the raw JS object and make sure it's not marked as form encoded. To do that, change the 'dataType' parameter to 'contentType' and update the data value to take the "stringified" version of the JSON object.
Like this:
data: JSON.stringify(pointData),
contentType: 'application/json',

Resources