I am trying to populate my CKeditor dialog selectbox with ajax. The following is from my plugin.js file:
...
{
type : 'select',
id : 'style',
label : 'Style',
setup : CKEDITOR.ajax.post( '.../ckeditor/plugins/simpleLink/ajax.php', JSON.stringify( { foo: 'bar' } ), 'application/json', function( data ) {
console.log( data);
}),
items : [ ['--- Select something ---', 0] ],
commit : function( data )
{
data.style = this.getValue();
}
}
...
The ajax output looks like this:
["Basketball","basketball"],["Baseball","baseball"],["Hockey","hockey"]
I am really wondering how to get the output INTO the "items". From my point of view I tried everything.
Can someone help me?
CKEditor select widgets have an 'add' function you can call to populate them. You can call it from an 'onLoad' function, if you add one:
{
type: 'select',
id: 'myselect',
label: 'The select will be empty until it is populated',
items: [ ],
onLoad: function(api) {
widget = this;
$.ajax({
type: 'GET',
url: 'path/to/your/json',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
for (var i = 0; i < data.length; i++) {
widget.add(data[i]['label'], data[i]['value']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ajax error ' + textStatus + ' ' + errorThrown);
},
});
},
},
Found a workaround. For anyone having the same problem - here is my way of solving it:
plugin.js:
This code before "CKEDITOR.plugins.add( 'PLUGINNAME', {..."
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
var results = $.getValues('.../ckeditor/plugins/PLUGINNAME/ajax.php');
This is the code for the select box
{
type : 'select',
id : 'style',
label : 'Style',
setup : '',
items : results,
commit : function( data )
{
data.style = this.getValue();
}
}
Related
good afternoon, have all of you, I have this problem. I am using selectr mobius1 and when I click to edit data, the "Type of Service" field does not show me the value that it should show me.
my select is initialized like this
$selecttSE = new Selectr("#tipo_SAPIE",{});
I use this onchange so that when a product is chosen the list of services changes
$("#tipo_productoE").on('change', function() {
var tipoprod = $("#tipo_productoE option:selected").val();
var select_servapi = $("#tipo_SAPIE");
$.ajax({
url: '<?= base_url('productos/select_servicios') ?>',
type: 'get',
data: {
tipoprod: tipoprod
},
beforeSend: function(){
$selecttSE.removeAll();
},
success: function(response) {
if (response.length >2 ) {
select_servapi.attr('disabled', false);
$.each(JSON.parse(response), function(i, item) {
$selecttSE.add([{
value: item.servicioapiid,
text: item.alias+' '+item.moneda+''+item.costo}])
});
let select = $("#tipo_SAPIE").parents().children('small')[0];
$(select).empty();
$(select).html('Requerido');
$(select).addClass('badge badge-soft-danger');
} else {
select_servapi.attr('disabled', true);
}
},
});
});
And my function to get the data is this
function getProducto(idproducto) {
var idproducto = idproducto;
$.ajax({
url: '<?= base_url('productos/getProducto') ?>',
type: 'GET',
data: {
idproducto: idproducto
},
success: function(response) {
console.log(response)
$selecttSE.removeAll();
$.each(JSON.parse(response), function(i, item) {
document.getElementById("tipo_productoE").value = item.tipoproductoid;
$("#tipo_productoE").trigger('change');
$selecttSE.setValue(item.servicioapiid);
});
},
error: function(errors) {
},
});
}
Thank you for taking the time to see my post have a great afternoon and much success.
the jquery Select2(Version: 3.5.4) plugin doesn't show my initial value which I loaded on the initSelection function of the plugin. Here is my code:
$("#materialFieldTags").select2({
tags: true,
initSelection : function (element, callback) {
console.log(element);
console.log(callback);
var countryId = "3"; //Your values that somehow you parsed them
var countryText = "mater3";
var data = [];//Array
var tempJSONMat = {
materials: []
};
$.ajax({
url: "php/FormProcessing.php",
type: "post",
data: "main=" + "materialFault" + "&faultid="+ main.faultId,
dataType: 'json',
success: function(data){
data.forEach(function(column) {
//console.log(column);
tempJSONMat.materials.push({
"id" : column.material_id,
"text" : column.name
});
});
}
});
callback(tempJSONMat.materials[0]);
},
ajax: {
type: "POST",
url: 'php/FormFilling.php',
dataType: 'json',
data: function (params) {
return "main=" + "allMaterials" + "&searchterm=" + params;
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
};
})
};
},
cache: true
}
});
Can you take I look at my code? Because I can't see it!! I also have try the:
$("#materialFieldTags").select2("data",mydata);
After the initialization of the plugin, but I am getting the same result.
Finally, I found my mistake! It was define two element by the same id, by mistake! The data appeared on first one and I was looking the second one.
I've got an AJAX url that returns data in the following format:
[{ "product": "Zip a dee doo dah", "desc": "F oq nfp gd r exbiikr wblkjm yumdd xy voqgt d hjtk. As sr ywvgiyb iqoibgm akron slfudtq smabx gj awlbtp ji vb do prvhlqq. ", "type": "Doodahs", "price": "3.99"}]
I'm trying to get the auto-complete to be based on the "product" entry.
Here is my code. It sends the request like it should, but I can't seem to get the auto-complete to populate the value based on 'product'. I'm sure I'm overlooking something stupid, but I've been staring at this for a few hours and figured its time to see if someone can help ;-).
Thanks for your help!
$(document).ready(function() {
$( "input[type='text']" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'POST',
data: 'q=' + prepareInput(this.element.attr('name') + '=' + request.term),
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
return $.map( data, function(item) {
var r = $.parseJSON(data);
return {
label: r['product'],
value: r['product']
};
});
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
});
--------------- Still not working, but current code below ------------------------
$(document).ready(function() {
$( "input[type='text']" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'POST',
data: 'q=' + prepareInput(this.element.attr('name') + '=' + request.term),
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
return $.map( data, function(item) {
console.log(item['product']);
return {
label: item['product'],
value: item['product']
};
});
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
Console.log is currently writing out the proper value, but the auto-complete still isn't popping up.
--- Working Code Below - Finally Got it Running. Thanks #Robert --------------
I was missing a number of things:
1) It needs to be an array, so I added [].
2) Apparently the format needs to be assigned to "response".
Now its working...
$(document).ready(function() {
$( "input[type='text']" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'POST',
data: 'q=' + prepareInput(this.element.attr('name') + '=' + request.term),
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
return $.map( data, function(item) {
response([{
label: item['product'],
value: item['product']
}]);
});
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
So you have an error on this line:
var r = $.parseJSON(data);
Post the output of console.log(data); //add this line bellow your success call
And change this line var r = $.parseJSON(data); to var r = $.parseJSON(item);
You are missing a single quote at end
prepareInput(this.element.attr('name'))
As the title suggests I would like to load remote data once only.
I thought about loading a data with independent ajax call and set it "locally" at the control but wonder if there is more "built in" way to do so...
a solution can be found here:
https://github.com/ivaynberg/select2/issues/110
$("#selIUT").select2({
cacheDataSource: [],
placeholder: "Please enter the name",
query: function(query) {
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData.result});
return;
} else {
$.ajax({
url: '/ajax/suggest/',
data: { q : query.term },
dataType: 'json',
type: 'GET',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data.result});
}
})
}
},
width: '250px',
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
Edit:
I might have misinterpreted your question. if you wish to load all data once, then use that is Select2, there is no built in functionality to do that.
Your suggestion to do a single query, and then use that stored data in Select2 would be the way to go.
This is for Select2 v4.0.3:
I had this same question and got around it by triggering an AJAX call and using the data returned as the initialized data array.
// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
// Text to let user know data is being loaded for long requests.
$('#mySelect option:eq(0)').text('Data is being loaded...');
$.ajax({
type: 'POST',
url: '/RetrieveDropdownOptions',
data: {}, // Any data that is needed to pass to the controller
dataType: 'json',
success: function(returnedData) {
// Clear the notification text of the option.
$('#mySelect option:eq(0)').text('');
// Initialize the Select2 with the data returned from the AJAX.
$('#mySelect').select2({ data: returnedData });
// Open the Select2.
$('#mySelect').select2('open');
}
});
// Blur the select to register the text change of the option.
$(this).blur();
});
This worked well for what I had in mind. Hope this helps people searching with the same question.
To load data once:
Assumptions:
You have a REST API endpoint at /services that serves a JSON array of objects
The array contains objects which have at least a "name" and "id" attribute. Example:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
You want to store that array as the global 'services_raw'
First, our function to load the data and create the global 'services_raw' (AKA 'window.services_raw'):
fetchFromAPI = function() {
console.log("fetchFromAPI called");
var jqxhr = $.ajax(
{
dataType:'json',
type: 'GET',
url: "/services",
success: function(data, textStatus, jqXHR) {
services_raw = data;
console.log("rosetta.fn.fetchServicesFromAPI SUCCESS");
rosetta.fn.refreshServicesSelect();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR);
setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds
}
}
)
.done(function () {
console.log("success");
console.log(jqxhr);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function () {
console.log("second complete");
});
};
Second, our Select2 instantiation code which transforms our data into a format that Select2 can work with:
refreshServicesSelect = function () {
// ref: http://jsfiddle.net/RVnfn/2/
// ref2: http://jsfiddle.net/RVnfn/101/ # mine
// ref3: http://jsfiddle.net/RVnfn/102/ # also mine
console.log('refreshServicesSelect called');
$("#add-service-select-service").select2({
// allowClear: true
data: function() {
var arr = []; // container for the results we're returning to Select2 for display
for (var idx in services_raw) {
var item = services_raw[idx];
arr.push({
id: item.id,
text: item.name,
_raw: item // for convenience
});
}
return {results: arr};
}
});
};
Here's what the Select2 element in HTML should look like before your call the above functions:
<input id="add-service-select-service" type="hidden" style="width:100%">
To use all of this, call (in JS):
window.fetchFromAPI();
window.refreshServicesSelect();
Lastly, here's a JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/
Basically, in my example above, we're just using ajax to populate the equivalent of window.pills in the Fiddle.
Hope this helps :)
Please reply if you know how to do this via the Select2 .ajax function, as that would be a bit shorter.
In my condition, it is working perfectly with the given code
$('#itemid').select2({
cacheDataSource: [],
closeOnSelect: true,
minimumInputLength: 3,
placeholder: "Search Barcode / Name",
query: function(query) {
// console.log(query);
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData});
return;
} else {
$.ajax({
url: "./includes/getItemSelect2.php",
data: { value : query.term },
dataType: 'json',
type: 'POST',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data});
}
});
}
},
});
And my data return from the ajax is in this form
<?php
$arr = [
["id" => 1, "text" => "Testing"],
["id" => 2, "text" => "test2"],
["id" => 3, "text" => "test3"],
["id" => 4, "text" => "test4"],
["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>
I'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});