i'm very desperate!
i have this problem with Bootstrap Typeahead.
HTML Markup:
<div class="form-group">
<label for="">Recipients</label>
<input id="recipients" name="recipients"
autocomplete="off"
class="form-control"
data-role="tagsinput">
</div>
JavaScript:
$('#recipientsContainer').tagsinput({
allowDuplicates: false,
trimValue: true,
confirmKeys: [13, 44],
typeahead: {
hint: true,
highlight: true,
minLength: 4,
limit: 10,
source: function (query) {
$.ajax({
url: "/app/route",
type: 'POST',
dataType: 'JSON',
data: {'query' : query},
success: function(data) {
console.log(data);
return(data);
}
});
},
afterSelect: function() {
this.$element[0].value = '';
}
}
});
After Ajax call I get this array in consolle:
["Justin Demetria +393281893574", "Dylan Alea +393700488191", "Zahir Tatyana +393007841301", "Ryan Veda +393542236060", "Hunter Wanda +393393156943"]
The problem is: I see nothing :( nothing appears. typeahead doesn't work.
In the console, I get this error
bootstrap-tagsinput.js Uncaught TypeError: Cannot read property 'success' of undefined.
How can I fix it?
I'm using Bootstrap 3, last Typeahead js source.
James, now my ajax call is:
$('#recipientsContainer').tagsinput({
allowDuplicates: false,
trimValue: true,
confirmKeys: [13, 44],
typeahead: {
source: function(queryForHints) {
if (queryForHints.length < 4)
return '';
var parameters = {'queryForHints': queryForHints};
jQuery.ajax({
url: "/app/route",
data: parameters,
type: "POST",
dataType: "json",
success: function(data) {
var sourceData = [];
for (var i = 0; i < data.length; i++) {
sourceData.push(data[i].text);
}
return (sourceData);
},
error: function(data) {
console.log("error for xxxxx/xxxxx");
},
async: true
});
}
}
});
But the error persist:
bootstrap-tagsinput.js:331 Uncaught TypeError: Cannot read property 'success' of undefined
the error is on bootstrap-tagsinput.js row 331, and i find:
if ($.isFunction(data.success)) {
// support for Angular callbacks
data.success(processItems);
Can we fix the problem ?
in my humble opinion, the problem is that input - tags can not understand the SUCCESS of an ajax call
For typeahead use Bloodhound to get your data not ajax.
Your code should look like something like this:
var customers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/customers?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#customer').typeahead({
minLength: 3,
highlight: true
}, {
name: 'customers',
display: 'name',
source: customers
}).on("typeahead:select", function(e, customer) {
vm.customerId = customer.id;
});
For more Information on Bloodhound:
Bloodhound#github
And here some examples for typeahead: TypeAhead Examples
Related
One of my legacy applications is using, Twitter typeahead to basically call an API and fetch the values based on the user input.
Now, I'm able to fetch the values fine. However, as I type the suggestions do not show up and the character types are cleared immediately. Can someone please suggest what am I doing wrong here?
Any input is highly appreciated. Thanks in advance.!
var $usersInput = $('#user');
var users_autoComp_conf= {
remote:{
url: 'https://my/url/fetch/users?s=%QUERY',
wildcard: '%QUERY',
transport: function(options, onSuccess, onError){
var url = options.url
$.ajax({
url: url,
type: "GET",
headers: {"x-api-key": apiKey},
success: function(response) {
//alert('success'+JSON.stringify(response));
if (response) {
_.each(response, function(item) {
return item;
});
}
},
error: function(response) {
alert('error'+response);
},
})
}
},
initialize: false,
identify: function(obj) {
return obj[$usersInput.attr('data-itemValue')]
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.obj.whitespace($usersInput .attr('data-itemText')),
sufficient: 5
}
var users_autoComp = new Bloodhound(users_autoComp_conf);
$usersInput.tagsinputcustom({
itemValue: $usersInput.attr('data-itemValue'),
itemText: $usersInput.attr('data-itemText'),
tagClass: function(item) {
if (item)
return 'api-tag label label-success';
else
return 'api-tag label label-warning toggle-confirmation';
},
focusClass: 'tags-focus',
typeaheadjs: [{
minLength: $usersInput.attr('data-nChar'),
highlight: true,
hint: true,
classNames: {},
autoselect: true,
clearQuery: true
}, {
name: $usersInput.attr('name'),
source: users_autoComp ,
limit: $usersInput.attr('data-max-items') || 1000,
display: function(item) {
return item[$usersInput.attr('data-itemText')]
},
templates: {
notFound: '<div class="empty-message">INVALID - NO DATA</div>',
suggestion: Handlebars.compile($usersInput.attr('data-displayTemplate'))
}
}]
});
I'm trying to get the data through ajax for tagify whitelist. but I get the following mistake
ReferenceError: Can't find variable: clist
code is:
$.ajax({
url: '/ajaxget/tags',
method: 'GET',
data: {
<?= csrf_token() ?> : '<?=csrf_hash()?>'
},
success: function(response) {
var clist = response;
//alert(response);
}
});
var input = document.querySelector('input[name="tags"]');
tagify = new Tagify(input, {
enforceWhitelist: true,
whitelist: clist,
maxTags: 5,
dropdown: {
maxItems: 5,
classname: "tags-look",
enabled: 0,
closeOnSelect: false
}
});
when I test it with "alert (response);" displays the data - ['123','333','763',asd']
You are trying to access a local variable from callback response as global variable.
$.ajax({
url: '/ajaxget/tags',
method: 'GET',
data: {
<?= csrf_token() ?> : '<?=csrf_hash()?>'
},
success: function(response) {
var clist = response;
populateList(clist);
}
});
function populateList(clist) {
var input = document.querySelector('input[name="tags"]');
tagify = new Tagify(input, {
enforceWhitelist: true,
whitelist: clist,
maxTags: 5,
dropdown: {
maxItems: 5,
classname: "tags-look",
enabled: 0,
closeOnSelect: false
}
});
}
I am trying to use js grid for my application. I am trying to populate the grid after ajax request but it do not seem to work as expected.
I am trying with SQL Server as back end and web application is asp.net MVC
This is my code in the html
var table;
var result;
var $j = jQuery.noConflict();
$j(document).ready(function () {
table = $j('#grid').jsGrid({
height: "60%",
width: "50%",
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
controller: {
loadData: function (filter) {
var d = $j.Deferred();
$j.ajax({
type: "POST",
contentType: "application/json",
url: "#Url.Action("LoadData", "User")",
datatype: "json",
data: filter
#*success: function (data) {
result = data.data;
console.log("result", result);
d.resolve(result)
},
error: function (data) {
window.location.href = '#Url.Action("Error", "Audit")';
}*#
}).done(function (data) {
console.log("response", data);
console.log("data.data", data.data);
d.resolve(data)
});
return d.promise();
},
fields: [
{ name: "LastName", type: "text"},
{ name: "FirstName", type: "text"},
{ name: "Email", type: "email"},
{ name: "PhoneNumber", type: "number"},
{ type: "control" }
]
}
});
});
In Controller I return
''return Json(new { data }, JsonRequestBehavior.AllowGet);''
I expect the json data to bind in the div. But it did not ? Thanks
Ok, so I've had this problem recently.
First off, change your "height" to px, auto, or get rid of it entirely. It's not doing what you think it's doing.
Next, since you have paging, you need to return your data in the following format:
{
data: [{your list here}],
itemsCount: {int}
}
It's barely in the documentation, as it's inline and not very obvious. (Bolding mine.)
loadData is a function returning an array of data or jQuery promise that will be resolved with an array of data (when pageLoading is true instead of object the structure { data: [items], itemsCount: [total items count] } should be returned). Accepts filter parameter including current filter options and paging parameters when
http://js-grid.com/docs/#controller
I have a Kendo grid that is being generated in an external javascript file as well as having data bound to it, and I been getting
Uncaught TypeError: Cannot read property 'uid' of undefined(anonymous function)
I have no idea where this 'uid' is coming from, I have been stepping through the code and and I think the error is coming in when trying to pass the returned data to the datasource of the grid.
My grid is this (and the grid does appear in the view)
function ShowAdministratorsGrid() {
$("#adminGrid").kendoGrid({
dataSource:[{
data: GetAdministratorsInformation()
}],
columns: [{
field: "AdministratorName",
title: "AdministratorName"
},
{
field: "DateCreated",
title: "DateCreated"
},
{
field: "CreatedBy",
title: "CreatedBy"
}],
Scrollable: true,
Sortable: true,
Pageable: [{
Refresh: true,
PageSizes: true,
ButtonCount: 5
}],
Selectable: true,
Events: function (e) {
e.onRowSelect();
}
})
}
The datasource data is this
function GetAdministratorsInformation() {
$.ajax({
type: "GET",
url: AddURLParam.AddGetAdminInformationURL,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
GetAdministratorData(data);
}
})
}
The GetAdministratorData function is this..
function GetAdministratorData(admindata) {
administratorName = admindata.administratorName,
dateCreated = admindata.dateCreated,
createdBy = admindata.createdBy
}
I am getting the returned data, as you can see in ScreenShot1
If you take a look at ScreenShot2, I am getting an undefined when adding the returned values to the GetAdministratorData, here is the screenshot
So I am thinking that is why I am getting the error on populating the KendoGrid, does anyone see what I am doing wrong or where things are going wrong?
EDIT
I narrowed down where the error is being thrown..
data is an array. so you need to access the item by admindata[0].administratorName.
Or loop through the array, I don't really know what you're trying to do. In any case, data is an array, which (right now) just contains the one object.
Also, on this line
dataSource:[{
data: GetAdministratorsInformation()
}],
GetAdministratorsInformation doesn't really return anything since it's an async operation. If you want to set the data, you'll need to do it on your success callback in GetAdministratorsInformation
And in your columns settings, the field names are pascal case AdministratorName while in the data object they're camel case administratorName
To recap:
function CreateAdministratorsKendoGrid(administratorData) {
$("#adminGrid").kendoGrid({
dataSource:[{
data: administratorData
}],
columns: [{
field: "administratorName",
title: "Administrator name"
},
{
field: "dateCreated",
title: "Date created"
},
{
field: "createdBy",
title: "Created by"
}],
Scrollable: true,
Sortable: true,
Pageable: [{
Refresh: true,
PageSizes: true,
ButtonCount: 5
}],
Selectable: true,
Events: function (e) {
e.onRowSelect();
}
})
}
function InitializeAdministratorsGrid() {
$.ajax({
type: "GET",
url: AddURLParam.AddGetAdminInformationURL,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
CreateAdministratorsKendoGrid(data);
}
})
}
InitializeAdministratorsGrid();
Resolved issue as follow:
var objectDDL = e.container.find("select:eq(0)").data("kendoDropDownList");
var rows = jQuery.makeArray(objectDDL.dataSource.data());
$.each(rows, function (index, value) {
objectDDL.dataSource.remove(rows[index]);
});
I'm using select2 plugin with remote ajax data. I can see the results in the dropdown but can't select them. I want the results to be selectable and placed into the field after selection. I think the problem is with passing the id, I don't know how to pass it correctly.. Any ideas?
my json for ?tag_word=for ...there is no id
results: [{text: "fort"}, {text: "food"}]
Here the code:
<select class="js-data-example-ajax" style="width:100%">
<option selected="selected">asdasd</option>
</select>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script type="text/javascript" src="{% static 'js/select2.js' %}"></script>
<script >
$(document).ready(function(){
$('.js-data-example-ajax').select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
cache: true,
ajax: {
url: '/tags/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { tag_word: parms.term }; },
},
});
});
</script>
here is the server code:
def autocomplete(request):
s = SearchQuerySet(using='autocomplete')
sqs = s.autocomplete(content_auto=request.GET.get('tag_word'))[:5]
suggestions = [ {'text':result.tag_word,
'id':result.tag_word,} for result in sqs]
the_data = json.dumps({
'results': suggestions
})
return HttpResponse(the_data, content_type='application/json')
To select an option each and every result need to have a unique id. Therefore you can add id using following code(processResults).
$('.js-data-example-ajax').select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
cache: true,
ajax: {
url: '/tags/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { tag_word: parms.term }; },
processResults: function (data) {
data.results.forEach(function (entry, index) {
entry.id = ''+index; // Better if you can assign a unique value for every entry, something like UUID
});
return data;
},
cache: true
},
});
Its a quick hack. Not sure how you could get along with select2 documentaion. But the following code worked with me in my localhost.
$(document).ready(function(){
$.get("json/select.json",function(data){ //specify your url for json call inside the quotes.
for(var i = 0; i < data.length; i++){
data[i]={id:i,text:data[i].text}
}
$(".js-data-example-ajax").select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
data: data
})
});
}
Its because you got all id's null. change to numbers. Click on the get selected button to see the ids only will be passed.
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$(document).ready(function(){
$('.js-data-example-ajax').select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
data: data
});
});
$(".checkoutput").click(function(){
console.log($('.js-data-example-ajax').val());
})
Here is the JSFIDDLE
Further to your final question on Alaksandar's answer, try adding his code like this:
$('.js-data-example-ajax').select2({
minimumInputLength: 2,
multiple:true,
delay: 250,
cache: true,
ajax: {
url: '/tags/search/autocomplete/',
dataType: 'json',
data: function (parms, page) { return { tag_word: parms.term }; },
success: function(results){
for(var i = 0; i < results.length; i++){
results[i] = {id:i,text:results[i].text}
}
}
},
});
I haven't tested any of this. So, if it works, please accept Aleksandar's answer as correct, not this one.