Results not displaying using ajax-select2 e - ajax

I have wriiten a code to display relevant serch results using select2 and ajax.The results are showing in console properly but not displayed in result table of select2.It just states no reults found...Below is my code:
<script type="text/javascript">
$(".showname").select2({
ajax: {
url:"http://hub.w.net/datatables/brand_processing",
//dataType: "json",
//delay: 250,
type:'POST',
data: function (params) {
return {
search_name: params.term // search term
//console.log(params:params);
};
},
processResults: function (data) {
// 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
console.log(data.data);
return {
data:{text:data.data,id:data.id}
};
},
cache: true
},
minimumInputLength: 1
});
</script>
Any suggestions?

try this for select2 latest version
processResults: function (data, params) {
var results = [];
if (data != null && data.length > 0) {
$.each(data, function (index, item) {
results.push({
id: item.id,
text: item.text
});
});
}
return {
results: results
};
};
for select2 3.5.2 version:
results: function (data, page) { // parse the results into the format expected by Select2.
var results = [];
if (data != null && data.length > 0) {
$.each(data, function (index, item) {
results.push({
id: item.id,
text: item.text
});
});
}
return {
results: results
};
},
cache: true
}

try this on processResults function
return {
text:data.data,
id:data.id
};

Related

select2 ajax dynamic search multipleselect - set values from respons on document ready

I have problem with passing data to select2 (ajax dynamic search) in edit mode on document ready.
I create test button which should add data on click and it doesnt work... Any ideas with that?
$('.select2').select2({
minimumInputLength: 3,
ajax: {
url: (...),
dataType: 'json',
data: function (params) {
return {
query: params.term
};
},
processResults: function (data, params) {
var resData = [];
data.forEach(function (value) {
if (value.name.toLowerCase().indexOf(params.term.toLowerCase()) != -1)
resData.push(value)
})
return {
results: $.map(resData, function (item) {
return {
text: item.name,
slug: item.slug,
id: item.id
}
})
};
},
},
});
$('#preselectObjectDataButton').on('click', function() {
var _array = []
var o = new Object;
o.id = 1;
o.text = "test";
o.slug = "test";
_array.push(o);
$('.select2').val(_array).trigger('change.select2');
});

select2 4.0.8, templateSelection option not working

I am using select2 version 4.0.8 with ajax search. In my angular 4 application with ajax call. Till searching and populating result it works fine. But after that when I click on any option it doesn't call method specified in templateSelection option.
Below is the code I am using:
jQuery(".suggestion"+i).select2({
placeholder: 'Select Countries',
ajax: {
url: AppConstants.facebookBaseUrl + "/search",
dataType: 'json',
delay: 250,
type: "GET",
beforeSend: (request)=> {
request.setRequestHeader("Authorization", "Bearer "+this.user.facebookPage_Token);
},
data: (params)=> {
return {
q: params.term, // search term
location_types: this.facebookFilters[i].filter,
type: "adgeolocation",
page: params.page
};
},
processResults: function (data, params) {
// 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, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
multiple:true,
minimumInputLength: 2,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo (repo) {
if (repo.loading) {
return repo.text;
}
var $container = jQuery("<option (click)='selectCountry($event)' class='country_name' value='"+repo.key+"'>"+repo.name+"</option>");
return $container;
}
function formatRepoSelection (repo) {
var $container = jQuery("<option class='selectedCountry' value='"+repo.key+"'>"+repo.name+"</option>");
return $container;
// return repo.key || repo.text;
}
And HTML:
<select class="form-control" name="selected[]" [ngClass]="'suggestion'+i"></select>
What I am doing wrong here?
thanks in advance!
Try by changing option to span as:
function formatRepoSelection (repo) {
var $container = jQuery("<span class='selectedCountry'>"+repo.name+"</span>");
return $container;
// return repo.key || repo.text;
}

Use select2 ajax data to update hidden inputs

I am having trouble updating hidden inputs using data retrieved from Select2 Ajax.
Please see my code:
var select2_town = $('.select-test select').select2({
ajax: {
url : ajax_var.url,
dataType: 'json',
type: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
};
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
id: item.id, //eg 1149
town: item.place_name, //eg Reading
county: item.county, //eg Berkshire
country: item.country,
data: item
};
})
};
},
cache: true;
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: function (item) { return ('<p>' + item.town + ' - ' + item.county + '</p>'); },
templateSelection: function (item) { return (item.town); },
});
This code works fine for me. My issue is what happens after a value is selected.
I would like to update my hidden input ids "#town","#county" and "#country" with town,county and country respectively through an 'change' event.
I have seen many SO examples but they all stop at $(this).select2('data')[0];but do not expand on it.
Weird thing is that the following script displays the correct value in console log. but ALWAYS only apply the object id to #country.
select2_town.on('change', function() {
var obz = $(this).select2('data')[0].country;
console.log(obz);//displays Reading in console
$("#country").attr("value",obz); //displays 1149
});
This actually works.
I had another function that was adding the ID hidden in another file. I deleted that and then the script worked as I wanted it to.
Regards
Thanks

flickr API does not provide any results

Hi I am trying this Flickr API, where I want to display title + image, for the first 3. But it's not working.
http://jsfiddle.net/28hEb/6/
var tag = "mount";
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=" + tag + "&tagmode=all& format=json&jsoncallback=?", function (data) {
$.each(data.items, function (index, item) {
$("<div>").html(item.title).appendTo("#content");
$("<img/>").attr("src", item.media.m).appendTo("#content");
if (index == 3) {
return false;
}
});
});
You have a syntax error:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "mount",
tagmode: "any",
format: "json",
}, function (data) {
var $content = $('#content');
$.each(data.items, function (i, item) {
$("<div>").html(item.title.m).appendTo($content);
$("<img/>").attr("src", item.media.m).appendTo($content);
if (i == 3) {
return false;
}
});
});
Check this fiddle
The } should end before the callback. Hence the issue. Your browser's console should give you a hint of what the error is.

Kendo UI reload treeview

I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven
try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();
I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '&notificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.

Resources