Issues with selectize.js and ajax - javascript

In my view i have the following code and i'm trying to get the select box to drop down with the values i send with the callback but unfortunately it does not work.
I was following http://maxoffsky.com/code-blog/laravel-shop-tutorial-3-implementing-smart-search/ with slight changes her and there to suite my use case.
<script>
$(document).ready(function(){
var root = '{{url("/")}}';
$('#testselect').selectize({
valueField: 'url',
labelField: 'description',
searchField: ['description'],
maxOptions: 10,
options: [],
create: true,
render: {
option: function(data, escape) {
return '<div>' + escape(data.description) + '</div>';
}
},
optgroups: [
{value: 'description', label: 'description'},
],
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: root+'/gettimecodes',
type: 'GET',
dataType: 'json',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
console.log(res.data) // Prints my data all well and good.
var object = {description:"description"};
var array = ["Saab", "Volvo", "BMW"];
var json = {
"data":[
{"description":"Saab"},
{"description":"Volvo"},
{"description":"BMW"}
]
}
// callback(array); // Doesn't work. (Array)
// callback(object); // Doesn't work (Object)
// callback(json); // Doesn't work (JSON)
}
});
},
});
});
</script>
If any one could point me in the correct direction it would be greatly appreciated!
Updated with bashers recomendations.
$('#testselect').selectize({
valueField: 'description',
labelField: 'description',
searchField: ['description'],
maxOptions: 10,
options: [],
create: true,
render: {
option: function(data, escape) {
return '<div>' + escape(data.description) + '</div>';
}
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/gettimecodes',
type: 'GET',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
callback(res.data)
}
});
},
});
The JSON that is returned in the response
{"data":[{"description":"Crushed blacks "},{"description":"Crushed blacks "},{"description":"Example of crushed blacks"},{"description":"Example of crushed blacks and video noise"},{"description":"Example of heavily de-interlaced artfacts on footage during title sequence - As source"}]}

Your valueField does not exist. url is not a property of the object you pass. Change valueField to description. Then let me know a more specific error if you get one. Also remove optGroups for now. Keep it basic.

Related

Jquery Datatables get row data as string or object on button click

I'm attempting to get a row of data based on button click event. I can manage to find the row and read the results as text, but I want the data cast as a string or an object. Below is my current code:
$.ajax({
url: "SympsService.asmx/GetSymptoms",
method: "post",
dataType: "json",
data: JSON.stringify({
organ_name: "toes"
}),
contentType: "application/json",
success: function(data) {
var sympList = 'GetSymptoms' ? JSON.parse(data.d) : data.d;
createDataTable('#symptomsTable', sympList);
function createDataTable(target, data) {
$(target).DataTable({
destroy: true,
paging: false,
searching: false,
info: false,
data: data,
columnDefs: [{
targets: [-1],
render: function() {
return "<button type='button'>" + ('Choose') + "</button>"
}
}],
columns: [{
'data': 'Sympt',
'title': 'toes Symptoms'
}, {
'data': null,
'title': 'Action'
}]
});
}
$('#symptomsTable').on("click", "tbody button", function() {
var id = $(this).closest("tr").find("td:nth-child(1)").text(); //this show perfectly
var id = $(this).closest("tr").find("td:nth-child(1)").data(); //this show undefined
var id = $(this).closest("tr").find("td:nth-child(1)").toString(); //this show {object Object}
console.log(id);
})
},
});
Any kind of help is appreciated.
To find the data object for the whole row:
$("#symptomsTable').DataTable().rows($(this).closest("tr")).data()
to find it for the particular cell:
$("#symptomsTable").DataTable().cells($(this).closest("td").siblings().eq(0)).data()

jsGrid won't render JSON data

I'm trying to use jsGrid in my MVC project as the client would like inline editing and filtering.
However, I cannot get it to load my JSON source into the table.
My js to load the table looks like so:
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "RICInstrumentCode/GetData",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
return $.ajax({
type: "CREATE",
url: "/api/RICInsrumentCodeTable",
data: item,
dataType: "json"
});
},
updateItem: function (item) {
return $.ajax({
type: "UPDATE",
url: "/api/RICInsrumentCodeTable/" + item.ID,
data: item,
dataType: "json"
});
},
deleteItem: $.noop
//deleteItem: function (item) {
// return $.ajax({
// type: "DELETE",
// url: "/api/data/" + item.ID,
// dataType: "json"
// });
//}
},
fields: [
{ name: "Code", type: "text", title: "RIC Instrument Code", width: 150 },
{ name: "Descr", type: "text", title:"RIC Instrument Code Description", width: 200 },
{ name: "RICInstrumentGroupId", type: "select", title: "RIC Instrument Group", items: countries, valueField: "Id", textField: "Name" },
{ name: "Active", type: "checkbox", title: "Is Active", sorting: true },
{ type: "control" }
]
});
});
The loadData is what I've been working on.
and the JSON the is returned from get data looks like so:
[{"Id":1,"Code":"test1","Descr":"first code test","RICInstrumentGroupId":2,"Active":true},{"Id":2,"Code":"APP","Descr":"Apples and bananas","RICInstrumentGroupId":4,"Active":true},{"Id":3,"Code":"1","Descr":"1","RICInstrumentGroupId":1,"Active":true},{"Id":4,"Code":"3","Descr":"3","RICInstrumentGroupId":3,"Active":false}]
So far I have confirmed that the ajax is firing, changed my array titles to match those of the call, and ensured the return is in valid JSON, what else can I do? Why isn't this working?
I was being stupid,
The bit that sets the table height was set to a 100% in a div that had no height, this was causing the table body to render with a height of 0px, changing the height property to auto fixed it because the data was there all along.
Thanks for the advice though!
I don't know if it is required, but when I look on demo examples (OData Service).
The grid loadData function looks bit different than yours.
loadData: function() {
var d = $.Deferred();
$.ajax({
url: "http://services.odata.org/V3/(S(3mnweai3qldmghnzfshavfok))/OData/OData.svc/Products",
dataType: "json"
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
is accept promise rather than ajax function. so that my be the problem
Demo here: http://js-grid.com/demos/

Select2 does not allow to select value while using select2 ajax

I am trying to use select2 for remote data in angularJS using select2-AJAX, it works fine when i use there given example on http://ivaynberg.github.io/select2/, but when I'm working with my own code, it does not allow me to select value.
$scope.select2Options = {
allowClear: true,
minimumInputLength: 3,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: rootURL.tsURL + "valueSets/dy346:fhir.observation-codes/concepts/_fhir",
dataType: 'json',
quietMillis: 250,
id: function(item) {
console.log(item);
return data.item['CodeableConcept.coding']['Coding.code'];
},
transport: function(params) {
params.beforeSend = function(request) {
request.setRequestHeader("Authorization", userService.tsConfig.headers.Authorization);
};
return $.ajax(params);
},
data: function(term, page) {
return {
criteria: term,
matchType: "StartsWith",
limit: "8",
offset: "0"
};
},
cache: true,
results: function(data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter the remote JSON data
var org = normalizeJSONLD.findAllObjectsByType(data['#graph'], "fhir:CodeableConcept");
var object = normalizeJSONLD.normalizeLD(data['#graph'], org);
return {
results: object
};
}
},
formatResult: function(item) {
console.log(item);
return item['CodeableConcept.coding']['Coding.code'] + ": " + item['CodeableConcept.coding']['Coding.display'];
},
formatSelection: function(item) {
return item['CodeableConcept.coding']['Coding.code'];
}
};
In Chrome Dev Tool, the select2 has a class "select2-result-unselectable" which does not allow me to select value.
You are only placing id function inside you ajax call, while it should be placed within the select2Options context as a key...
$scope.select2Options = {
allowClear: true,
minimumInputLength: 3,
ajax: {
url: rootURL.tsURL + "valueSets/dy346:fhir.observation-codes/concepts/_fhir",
dataType: 'json',
quietMillis: 250,
transport: function(params) {
params.beforeSend = function(request) {
request.setRequestHeader("Authorization", userService.tsConfig.headers.Authorization);
};
return $.ajax(params);
},
data: function(term, page) {
return {
criteria: term,
matchType: "StartsWith",
limit: "8",
offset: "0"
};
},
cache: true,
results: function(data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter the remote JSON data
var org = normalizeJSONLD.findAllObjectsByType(data['#graph'], "fhir:CodeableConcept");
var object = normalizeJSONLD.normalizeLD(data['#graph'], org);
return {
results: object
};
}
},
formatResult: function(item) {
console.log(item);
return item['CodeableConcept.coding']['Coding.code'] + ": " + item['CodeableConcept.coding']['Coding.display'];
},
formatSelection: function(item) {
return item['CodeableConcept.coding']['Coding.code'];
},
// id should be defined over here...
id: function(item) {
console.log(item);
return data.item['CodeableConcept.coding']['Coding.code'];
}

Pass complex javascript object configuration(data and functions) from json string

I have a javascript that has a bunch of parameters and functions inside of it.
ctrl.kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
url: "odata/CodeView",
dataType: "json",
contentType: "application/json"
},
update: {
url: function (data) {
return "api/CodeMapUpdate/" + data.CODE_MAP_ID;
},
dataType: "json",
type: "post",
complete: function (e) {
ctrl.data("kendoGrid").dataSource.read();
if (e.status == 201) {
logger.log("Record Updated: Record ID = " + e.responseJSON, null, null, true);
} else {
logger.logError(" Save failed " + e.responseJSON.ExceptionMessage, null, null, true);
}
}
},
destroy: {
url: function (data) {
return "api/CodeMapDelete/" + data.CODE_MAP_ID;
},
dataType: "json",
complete: function () {
ctrl.data("kendoGrid").dataSource.read();
}
},
create: {
url: "api/CodeMapCreate",
dataType: "json",
complete: function (e) {
ctrl.data("kendoGrid").dataSource.sort({
field: "CODE_MAP_ID",
dir: "desc"
});
ctrl.data("kendoGrid").dataSource.filter({});
if (e.status == 201) {
logger.log("Record Created: Record ID = " + e.responseJSON, null, null, true);
} else {
logger.logError(" Save failed " + e.responseJSON.ExceptionMessage, null, null, true);
}
}
},
},
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data["odata.count"];
},
model: {
id: "CODE_MAP_ID",
fields: {
CODE_MAP_ID: {
editable: false,
type: "number"
},
CODE_NAME: {
type: "string",
validation: {
title: "Required Field",
required: true
}
},
L_NAME: {
type: "string",
validation: {
required: true
}
},
CODE_DATE: {
field: "CODE_DATE",
type: "date",
format: "{0:MM/dd/yyyy}",
validation: {
required: true
}
},
}
}
},
change: function () {
},
//batch: true,
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
sort: {
field: "CODE_MAP_ID",
dir: "desc"
}
//autoSync: true
} })
I am trying to save the entire "dataSource" object as a variable and retrieve it at runtime with ajax.
I am able to do this with eval ("(" + dataSource + ")") but any included functions are no longer executing.
Any idea on a strategy to store/retrieve this type of an object to/from JSON?
here is a simple demo of how to use the 2nd param to JSON.parse to recover stored functions:
var ob={a:1, b:false, c: function(a){ return a * a;} };//a sample object
Function.prototype.toJSON=Function.toString; //extend JSON to cover Functions
var str=JSON.stringify(ob, null, "\t"); //turn sample object into a string:
/* str =={
"a": 1,
"b": false,
"c": "function (a){return a*a;}"
} */
//now turn the string back into an object, using a reviver to re-parse methods:
var ob2=JSON.parse(str, function(a,b){
if(b.match && b.match(/^function[\w\W]+\}$/)){ b=eval("b=0||"+b); }
return b;
});
var n=5; //let's try the method using a number
var n2=ob2.c(5); //apply the method to the number
alert(n2); // shows: 25, the number times itself, verifying that the function works
You might want to be a litle stricter about what you send to eval, maybe use a key schema in addition to matching properties that simply look like functions. you can beef-up the regexp to be a little stricter, but for this quick demo of the JSON.parse() parameter, it all works just fine.
In this case, since you are collecting the properties of the JSON, there's no chance of running into the security issues that eval() use can facilitate. Those problems stem from sending one user's input to another user without filtering, not when you jump-start code the client itself produced last time...

Select2: how to set data after init?

I need to set an array of data after initializing select2. So I want to make something like this:
var select = $('#select').select2({});
select.data([
{id: 1, text: 'value1'},
{id: 1, text: 'value1'}
]);
But I get the following error:
Option 'data' is not allowed for Select2 when attached to a element.;
My HTML:
<select id="select" class="chzn-select"></select>
What should I use instead of a select element?
I need to set the source of items for search
In onload:
$.each(data, function(index, value) {
$('#selectId').append(
'<option value="' + data[index].id + '">' + data[index].value1 + '</option>'
);
});
Make an <input type="hidden"> element and bind select2 to that. Using .select2 on a regular select box doesn't let you play with the data, it just mostly gives you the UI and post-selection methods.
Source:
Select2 Documentation
Source: https://select2.org/programmatic-control/add-select-clear-items
Add item:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
Clear items:
$('#mySelect2').val(null).trigger('change');
For v4 you'll have to destroy and reconstruct select2 with updated data. Check https://github.com/select2/select2/issues/2830
I've recently had the scenario where changing one select2 object alters the contents of a second (parent - child groupings effectively). I used an ajax call to retrieve a new set of Json data, which was then picked up by the second select2 object. I've included the code below:
$("#group").on('change', function () {
var uri = "/Url/RetrieveNewResults";
$.ajax({
url: uri,
data: {
format: 'json',
Id: $("#group :selected").val()
},
type: "POST",
success: function (data) {
$("#groupchild").html('');
$("#groupchild").select2({
data: data,
theme: 'bootstrap',
placeholder: "Select a Type"
});
},
error: function () {
console.log("Error")
}
});
});
I found that I had to include the $("#groupchild").html('') in order to clear out the previous set of data in the second select2. Hope this helps.
You can rerender and trigger the select2
render select2
$('.select2').select2({
placeholder: 'Slect value',
allowClear: true
});
after need to change the data data
let dataChange = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 2,
text: 'duplicate'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
rerender the select2
$('.select2').select2('destroy');
$('.select2').empty();
$('.select2').select2({
placeholder: 'Slect value',
allowClear: true,
data: dataChange
});
trigger select2
$('.select2').trigger('change');
Hope this is the answer for you :3
Here's what I did.
1. Extend select2
Select2.prototype.setAjax = function (ajaxOptions)
{
// Set the new ajax properties
var oAjaxOpts = this.options.get('ajax');
if (oAjaxOpts != undefined && oAjaxOpts != null)
{
for (var sKey in ajaxOptions)
{
oAjaxOpts[sKey] = ajaxOptions[sKey];
}
}
var DataAdapter = this.options.get('dataAdapter');
this.dataAdapter = new DataAdapter(this.$element, this.options);
}
2. Initialize as usual (for example --- yours could be different)
jHtmlFrag.select2({
dropdownParent: $(oData.jDiv),
placeholder: "Select Option",
allowClear: true,
minimumInputLength: 2,
ajax: {
url: "",
method: "POST",
dataType: 'json',
delay: 250,
processResults: function (oResults, params)
{
let page = params.page || 1;
// console.log(oResults, (params.page * 10));
return {
results: oResults.data,
pagination: {
more: (page * 10) < oResults.recordsFiltered
}
};
}
}
}).val(null).trigger('change');
3. Set Ajax options dynamically when you feel like by calling the new extension func
jCombo.select2('setAjax', {
url: sUrl,
data: function (params)
{
let query = {
search: params.term,
type: params._type,
page: params.page || 1,
}
return query;
},
});

Categories

Resources