How to define select2 default AJAX value?
I've tried many but still cannot get it working.
Below is my code:
$("#qrcode_group_rowid").select2({
ajax: {
url: "app/qrcode/qrcode_group_select_service.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 50) < data.total_count
}
};
},
cache: true
},
placeholder: 'Please select',
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 0,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo (json) {
if (json.loading) {
return json.text;
}
var markup = json.group_name;
return markup;
}
function formatRepoSelection (json) {
return json.group_name;
}
and my JSON data:
{
"total_count": 897,
"items": [{"id": 901,"group_name": "TEST25-117"},{"id": 1,"group_name": "TEM117"}]
}
What am I doing wrong and how can I fix it?
You should send the following information in the PHP method (there may be a limitation of working with the IP address in eloquent)
/** #var Collection $btsNodes */
$btsNodes = BtsNode::where('node_code' , 'like' , '%'.$request->get('q').'%')
->get(['node_code']);
// ->toArray();
$items = $btsNodes->map(function ($item){
return [
'id' => $item['node_code'],
'node_code' => $item['node_code']
];
});
return ['items' => $items];
Related
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');
});
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;
}
I'm using ajax and successfully getting the response. I'm unable to understand, why if-else condition is not returning boolean value as expected. Not sure, if I'm using the return in right place or not. Need help.
validateEverPresentRowWidgetValue: function (datafield, value, rowValues) {
if ((!value)) {
$.alert({
content: 'Please select Date!',
btnClass: 'btn-warning',
boxWidth: '30%',
title: 'Missed something!',
type: 'orange',
typeAnimated: true,
useBootstrap: false
});
return false; //Works fine
} else if (value) {
$.ajax({
url: 'checkForLeave.php',
dataType: 'json',
method: 'post',
data: {date: value},
success: function (response) {
if (response.length > 0) {
$.confirm({
title: 'Confirm!',
content: 'This date is NOT allowed! <br> Reason:' + response[0].comments,
boxWidth: '30%',
typeAnimated: true,
useBootstrap: false,
btnClass: 'btn-warning',
type: 'orange',
buttons: {
confirm: function () {
return true; //Problem in return
},
cancel: function () {
return false; //Problem in return
}
}
});
} else {
return true;
}
},
error: function (response) {
return false;
}
});
}
}
I want to load items by page since I have tables with large amount of data, but I don't want to load items for each page once the user clicks it.
Instead, I rather preload 1000 items (for example) ahead and only fetch more results if the user moves to a page I still didn't fetch the data for.
Is it possible?
I found a way to solve it.
Here is the basic logic:
Create a local data cache object that will hold arrays of results for each page.
When fetching data from the server, always return data for a few pages ahead and store them in the local cache object
Write a method for the controller.loadData that will check to see if you have the desired page results in the local cache object, if so - return that array, if not - return a promise that will fetch the results with some extra data for a few pages ahead.
An example of the local cache object snapshot:
{
"1": [{name: "ff"}, {name: "fdd"}],
"2": [{name: "fds"}, {name: "dsr"}],
"3": [{name: "drr"}, {name: "ssr"}]
}
script section
<script type="text/javascript">
$(document).ready(function () {
List();
});
function List() {
//$(function () {
loadjsgrid();
$("#jsGrid").jsGrid({
height: "auto",
width: "100%",
filtering: true,
editing: false,
sorting: true,
autoload: true,
paging: true,
pageSize: 10,
pageButtonCount: 5,
pageLoading: true,
controller: {
loadData: function (filter) {
var startIndex = (filter.pageIndex - 1) * filter.pageSize;
var d = $.Deferred();
$.ajax({
type: 'GET',
url: '#Url.Action("[ActionName]", "[Controllername]")',
data: filter,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
if (data.Message == "Failed") {
data.Result = [];
data.Count = 0;
}
console.log(data);
d.resolve(data);
}
});
return d.promise().then(function (q) {
return {
data: q.Result,
itemsCount: q.Count
}
});
}
},
},
fields: [
{ name: "rct_no", type: "text", title: 'Serial Number', autosearch: true, width: '10%' }
],
});
$("#pager").on("change", function () {
var page = parseInt($(this).val(), 10);
$("#jsGrid").jsGrid("openPage", page);
});
}
Controller section
public ActionResult getList(int pageIndex = 1, int pageSize = 10)
{
try
{
var query = #" from rd_receipt_header
var irList = DAL.db.Fetch<[className]>(pageIndex, pageSize, #"select * " + query );
var count = DAL.db.ExecuteScalar<int>("select count(*) " + query);
return Json(new { Message = "Success", Result = irList, Count = count }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex) { return Json(new { Message = "Failed", Result = ex.Message }, JsonRequestBehavior.AllowGet); }
I am using ajax to get data from server as ajax format
I am trying to populate data into Select2 dropdown using JSON which is returned by a controller class.But it is not working.There is no error.Here is the code
client Side
$("#products").select2({
minimumInputLength: 2,
ajax: {
url: "Search",
dataType: 'json',
type: "POST",
quietMillis: 50,
data: function (term) {
return {
"q": JSON.stringify(term),
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
Controller Action
[HttpPost]
public JsonResult Search(string q)
{
//testing data
return Json(new products() {id = "2", text = "biotouch"});
}
Product class
public class products()
{
public string id{get;set;}
public string text{get;set;}
}
It worked when I changed
results: function (data) {
to
ProcessResults: function (data) {
$("#products").select2({
minimumInputLength: 2,
ajax: {
url: "YourControllerName/Search",
dataType: 'json',
type: "POST",
quietMillis: 50,
data: function (term) {
return {
"q": JSON.stringify(term),
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
I have added controller name in URL you forgot to add controller name in url.