BS Typeahead doesn't show results - javascript

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:
$('#recipients').tagsinput({
allowDuplicates: false,
trimValue: true,
confirmKeys: [13, 44],
typeahead: {
source: function(queryForHints) {
if (queryForHints.length < 4)
return '';
var parameters = {
'queryForHints': queryForHints
};
jQuery.ajax({
url: "/xxxx/xxxx",
data: parameters,
type: "POST",
dataType: "json",
success: function(data) {
return (data);
},
error: function(data) {
console.log("error for xxxxx/xxxxx");
},
async: true
});
}
}
});
After Ajax call I get this array:
[{
"value": "+393334029137",
"text": "Dean Leandra (+393334029137)"
}, {
"value": "+393333419836",
"text": "Alfonso Erasmus (+393333419836)"
}, {
"value": "+393173833341",
"text": "Travis Aquila (+393173833341)"
}, {
"value": "+393334998841",
"text": "Conan Preston (+393334998841)"
}]
The problem is: I see nothing :( nothing appears. typeahead doesn't work.
In the console, I get this error
bootstrap-tagsinput.js:331 Uncaught TypeError: Cannot read property
'success' of undefined
Can you help me solve this?

success: function(data) {
var sourceData = [];
for (var i = 0; i < data.length; i++) {
sourceData.push(data[i].text);
}
return (sourceData);
What you have from your JSON response is an object array. You want to see text as a suggestion I assumed. So you need to get text from your object because typeahead source expects a string array. Push text values into another string array and return it. I haven't tested the code yet but it should work for you.
Another issue you have is that you are making an AJAX call which is async. That's why you have undefined from success.

Related

JQuery DataTables Columns Initializing automatically with data

I have a JQuery DataTable and I have been using it for a while, I guess I am missing something here.
However I came into one of the requirement recently to directly bind with JSON Data.
My JSON for example looks like i.e. coming from API :
[{"componentNumber":"ABC","factory":"India","productNumber":"CR","productRevisionState":"123","placementTimeLocal":"2018-08-21T00:00:00","position":"up"},{"componentNumber":"ABC","factory":"India","productNumber":"CR","productRevisionState":"123","placementTimeLocal":"2018-08-21T00:00:00","position":"up"},
{"componentNumber":"ABC","factory":"India","productNumber":"CR","productRevisionState":"123","placementTimeLocal":"2018-08-21T00:00:00","position":"up"}]
I know that I can use JSON and take columns out in Jquery and pass it to the Datatables columns but what I am looking if there is a simple way where Datatable takes column automatically something like:
$.ajax({
type: "Post",
url: "http://localhost:5555/myapi",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//datasource = data;
$('#myTable').DataTable({
"Data": JSON.parse(data),
"Columns" : JSON.parse(data)
});
},
error: function (err) {
alert(err);
}
})
What I am looking is that:
Does JQuery have any such features or not? If not can you suggest
any other Datatable library which is fast for large dataset.
I want to get rid of all extra looping around the code
I can't update source system from where data is getting returned
Updated Version of Code, took from below answers, thanks Kiran for making me move a bit:
$.ajax({
type: "Post",
url: "http://localhost:5555/myapi",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// **how to get rid of this loop? for looping columns**
var adColumns = [];
$.each(data[0], function (i, item) {
var col = {
data: i,
title: i
};
adColumns.push(col);
})
//datasource = data;
console.log(data);
$('#myTable').DataTable({
"data": data,
"info": true,
"paging": true,
"columns": adColumns
});
},
error: function (err) {
alert(err);
}
})
try the following code. It may help you to achieve the desired result. This may not be an optimized code.
Hope this helps.
EDIT
At least one loop will be required to create the array of column names.So you can also use the following code to eliminate multiple loops.
var adColumns = [];
Object.keys(strData[0]).forEach(key => {
var col = {
data: key,
title: key
};
adColumns.push(col);
});
$(function() {
var strData = [{
"componentNumber": "ABC",
"factory": "India",
"productNumber": "CR",
"productRevisionState": "123",
"placementTimeLocal": "2018-08-21T00:00:00",
"position": "up"
}, {
"componentNumber": "ABC",
"factory": "India",
"productNumber": "CR",
"productRevisionState": "123",
"placementTimeLocal": "2018-08-21T00:00:00",
"position": "up"
},
{
"componentNumber": "ABC",
"factory": "India",
"productNumber": "CR",
"productRevisionState": "123",
"placementTimeLocal": "2018-08-21T00:00:00",
"position": "up"
}
];
/*var dta = strData;
var tableColumnNames = [];
var keys = [];
for (var i in strData) {
var key = i;
var val = strData[i];
for (var j in val) {
var sub_key = j;
keys.push(sub_key);
}
}
var sColumns = Array.from(new Set(keys));
var adColumns = [];
for (var col in sColumns) {
var sKey = sColumns[col];
var col = {
data: sKey,
title: sKey
};
adColumns.push(col);
}*/
var adColumns = [];
Object.keys(strData[0]).forEach(key => {
var col = {
data: key,
title: key
};
adColumns.push(col);
});
$('#myTable').DataTable({
"data": strData,
"columns": JSON.parse(JSON.stringify(adColumns))
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="myTable">
</table>
DataTables has the ability to read data from virtually any JSON data source that can be obtained by Ajax. This can be done, in its most simple form, by setting the ajax option to the address of the JSON data source. See This Link in DataTable Website.
As for your JSON, here is a fiddle

How can I get response from webservice in jquery?

I want to get the data response from my login webservice. Here is my web service
http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a
(for testing). Here is my code:
$("#login").click(function () {
var url = "http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a";
$.ajax({
url: url,
type: 'Get',
success: function (data) {
alert(data.Medical_id);
},
});
});
The alert() shows me undefined. Please advise on what the problem could be.
The result is an array, so in order to get that field you have to iterate the result or get the first item:
for (var i in data) {
console.log(d[i].Medical_id);
}
Or you can simply get the first result:
$.ajax({
url: 'http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a',
type: 'Get',
success: function (data) {
alert(data[0].Medical_id);
}
});
The JSON result you are getting is :
[{"$id":"1","id":8,"Medical_id":"a","Password":"a","Name":null,"Email":null,"gender":null,"Type":null}]
use for each to iterate through the results or
instead of this you can check the result like this :
var data = [{ "$id": "1", "id": 8, "Medical_id": "a", "Password": "a", "Name": null, "Email": null, "gender": null, "Type": null }]
alert(data[0].Medical_id);
If you develop application in localhost then refer this questions also.
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
If you are using chrome, then use this link to use CORS enable plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US
hope this will help

jsTree - Populate Tree Dynamically using AJAX/C#Web Method

I have a div which I would like to fill with a jsTree:
I get the "Loading" icon where the tree is meant to display, however, there would seem to be a javascript error, even though one is not thrown.
I load my folder structure from an AJAX Request as follows. The Documents.aspx/GetFolders Web Method returns a List containing FolderId, ParentId & Folder Name. I have debugged the web method and it is passing the correct results to the jsTree "data" function.
$.ajax({
type: "POST",
url: 'Documents.aspx/GetFolders',
contentType: "application/json; charset=utf-8",
success: function (data) {
data = data.d;
$("#tree").jstree({
"core": {
"themes": {
"responsive": true
},
"data": function () {
var items = [];
items.push({ 'id': "jstree_0", 'parent': "#", 'text': "Documents" });
$(data).each(function () {
items.push({ 'id': "jstree_" + this.DocumentFolderId, 'parent': "jstree_" + this.ParentId, 'text': "" + this.Name });
});
return items;
}
},
"types": {
"default": {
"icon": "fa fa-folder icon-lg"
},
},
"plugins": ["contextmenu", "dnd", "state", "types"]
});
},
error: function () {
toastr.error('Error', 'Failed to load folders<span class=\"errorText\"><br/>There was a fatal error. Please contact support</span>');
}
});
After debugging the code, it seems the data is being retrieved correctly and is returning the object array as intended.
Is there are any problem with the above (or is there somewhere else I should be looking)? Or is there a better method of achieving its intended purpose?
I think I have finally found the answer! :)
"core": {
"themes": {
"responsive": true
},
"data": {
type: "POST",
url: "Documents.aspx/GetFolders",
contentType: "application/json; charset=utf-8",
success: function (data) {
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
},
}
Server side, you need to return the data in the array format required, i.e:
[{id = "node0", parent = "#", text = "Documents"},
{id = "node1", parent = "node0", text = "Public"},
{id = "node2", parent = "node0", text = "Restricted"}]
Just in case anyone has the "loading..." issue, this format fixed it for me when returning data.
[{"id":"node0", "parent":"#", "text":"Documents"},
{"id":"node1", "parent":"node0", "text":"Public"},
{"id":"node2", "parent":"node0", "text":"Public"}]

Select 2 displaying undefined using initSelection ajax call

I'm trying to preload an entry into Select2 using a remote ajax call and the initSelection function. My question seems to be similar to this question, however both answers don't work for me.
The call works and returns the correct result in json format, the issue appears to be with the callback not sending the data object in the right format.
j("#selectElement").select2({
placeholder: "Placeholder text",
multiple: false,
minimumInputLength: 1,
ajax: {
url: "/getfiles",
dataType: 'json',
data: function (term, page) {
return {
q: term //search term
};
},
results: function (data, page) {
return data;
}
},
initSelection: function(element, callback) {
return j.getJSON("/getfiles?id=" + (element.val()), null, function(data) {
if (j.isFunction(callback)) {
//alert(JSON.stringify(data, null, 4));
return callback(data);
}
});
}
});
When I alert the data object it returns this data:
{
"results": [
{
"id": "1",
"text": "Name of the file"
}
],
"more": "false"
}
The end result is the text "undefined" being loaded into the select2 input.
I would greatly appreciate any assistance.
Tim
The solution is to format the callback data like this
return callback(data.results[0]);
Credit goes to this question/answer: Select2 and initSelection callback

Not able to access JSON data in ajax jquery

I have a Jquery AJAX POST method.Which call a web method of asp.net.
The ajax method get a json data.
The data format is :
[
{
"Title": "Test2",
"Name" : "AMIT",
"IsRoot": "True"
},
{
"Title": "Test3",
"Name" : "AMIT1",
"IsRoot": "False"
},
{
"Title": "Test4",
"Name" : "AMIT2",
"IsRoot": "True"
}
]
I validate the dataformat in "http://jsonlint.com/" site and it's telling that dataformat is correct.
I want to loop through the data and access each of the attribute.But I am not able to get that.
I try to find the total array length which should be 3.But it's giving me 9(means each attribute )
I try
alert(data.d.length); // giving 9 (should give 3)
var jsondata = data.d;
alert(jsondata[1].Title); //undefined (should give Test3)
alert(jsondata[2].Title); //undefined (should give Test4)
alert(jsondata[1].Name); //undreined (should give AMIT1)
var key, count = 0;
for (key in data.d) {
if (data.d.hasOwnProperty(key)) {
count++;
}
}
alert(count); // giving 9 (should give 3)
any help is highly accepted.
My ajax calling method is
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetRootData",
dataType: "json",
success: function (data, textStatus) {
var jsondata = data.d;
alert(jsondata[1].Title);
alert(jsondata[2].Title);
alert(jsondata[1].MimeType);
var key, count = 0;
for (key in data.d) {
if (data.d.hasOwnProperty(key)) {
count++;
}
}
alert(count);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
and don't know why debugger also not working.. :(
Thanks everyone.Finally I solved the problem.
the solution is
var jsonObject = eval(data.d);
Now it's returning all the data fine..
alert(jsonObject.length); //Now it's returning 2
alert(jsonObject[1].Title); // it's returning Test3 now.
Thanks..

Categories