I'm trying to use Typeahead. I'm using AJAX to get my source :
$(document).ready(function() {
$('input.typeahead').typeahead(
{
hint: true,
highlight: true,
minLength: 1
},
{
source: function(query, process) {
jQuery.ajax({
url: 'suggestion.php',
dataType: "json",
data: {
type: 'abc'
},
success: function(data) {
suggestion = [];
for(var i in data)
{
suggestion.push(data[i]);
}
console.log(data);
}
});
process(suggestion);
return suggestion;
}
});
});
But there is the result :
But when I see the logs :
I've an array with strings !
There the console message :
I can see an error appear at the first char typed but only the first time. All the time, I've "undefined" x 5 proposed.
What's the matter ? I guess the format, but I've tried mainly things from stacks, without results (only errors). My Php code return ("echo") an json_encode($array) ! It's my first time using Ajax and Typeahead..
Sorry for my english.
I think that suggestion must be this kind of array :
[{ "value": "CBOXXX" }, { "value": "CBAXXX" }]
Related
I try to make autocomplete with jquery filter by id category, when I type the result not showing, like this picture :
When I click tab network I've got the data like this picture :
This is my code javascript :
<script type="text/javascript">
$(function() {
$(".keyword").autocomplete({
source: function(request, response) {
$.ajax({
url: "search/autocomplete",
type: "GET",
dataType: "json",
data: {'id':1},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.name,
value: item.id
};
}));
}
});
},
select:function(event,ui) {
$(".keyword").val(ui.item.label);
return false;
},
minLength: 2,
}).bind('focus', function () {
$('.ui-autocomplete').css('z-index','9999').css('overflow-y','scroll').css('max-height','300px');
// $('.ui-autocomplete').css('background','#09121a').css('color','#fff');
// $('.ui-menu .ui-menu-item-wrapper').css('padding','11px 1em 3px 1.4em !important');
// $(this).autocomplete("search");
// var btncategory = $('.btn-category').width();
// var left = '-'+btncategory+'px';
});
});
</script>
If I type "a" - I don't see anything, but when I delete "a" - I see all three. So it's look like the jQuery doesn't know that it should look for a value in object.name.
As Tan Duong said, your response only contains the attribute called value. It is not able to find name and id, hence your results are showing blank data.
Change your success function to this:
success: function(data) {
response($.map(data, function(item) {
return {
label: item.value,
value: item.value
};
}));
}
I want to use typeahead to retrieve postal codes remotely and it must be post, not get. The call returns following json in the console:
{suggestions: "L-6956 | IM GRUND | KEEN-SUR-DOHEEM"}
{suggestions: "L-6956 | OP DER MOUCK | KEEN-SUR-DOHEEM"}
But the result is not shown under the input field in order to select one of the results. Here is my code:
$('#txtPostalCode').typeahead(
null,
{
name: 'txtPostalCode',
displayKey: 'suggestions',
minLength: 3,
source: function (query, syncResults) {
$.post('/hotbed/sggl/getpipedaddresses', {searchItem: query}, function (data) {
syncResults($.map(data, function (item) {
console.log(item.suggestions);
return item;
}));
}, 'json');
}
});
According to typeahead API, server response should be marked as an Async and your response should be fetched using that asyncCB,
$('#txtPostalCode').typeahead({
null
},
{
name: 'txtPostalCode',
displayKey: 'suggestions',
minLength: 3,
async: true,
source: function (query, processSync, processAsync) {
processSync(['This suggestion appears immediately', 'This one too']);
return $.ajax({
url: "/hotbed/sggl/getpipedaddresses",
type: 'POST',
data: {searchItem: query},
dataType: 'json',
success: function (json) {
// in this example, json is simply an array of strings
return processAsync(json);
}
});
}
});
since there is on open bounty for this question I cant mark it as duplicate but you might find more details at the following question,
Duplicate of this question
I am trying to write a test for a Javascript select2 control and I would like to automatically select the first item. Since it's using ajax I do not know what the first item is. All the examples I have seen create <option> however they assume knowledge of the value. How can I select the first item without knowledge? (Note this example only runs the ajax command after 3 items are entered).
var $selector = $("#foo");
$selector.show().select2({
allowClear: true,
placeholder: "--------",
minimumInputLength: 3,
ajax: {
url: "...",
type: 'GET',
dataType: 'json',
delay: 250,
data: function(term, page) {
return {
number__icontains: term
};
},
results: function(data) {
return {
results: $.map(data.objects, function(option) {
return {
'id': option.id,
'text': option.desc
};
})
};
},
cache: false
},
initSelection: function(element, callback) {
...
}
});
Just want to know why push method of the javascript inserts "index"
var agendaBatch=[];
for(var i=0; i<agendas.length; i++) {
var agenda = {
MeetingId: meetingId,
Title: agendas[i].title,
Description: agendas[i].description,
Remarks: "",
};
agendaBatch.push(agenda);
}
console.log(kendo.stringify(agendaBatch));
dataSourceAgenda.add(agendaBatch);
dataSourceAgenda.sync();
output:
{"0":{"Title":"Agenda title","Description":"Agenda details","Remarks":""},
"1":{"Title":"Agenda title","Description":"Agenda details","Remarks":""}}
what I expect is this output to match my Web API parameter requirement
[{"Title":"Agenda title","Description":"Agenda details","Remarks":""},
{"Title":"Agenda title","Description":"Agenda details","Remarks":""}]
Any suggestions how can I do this?....
UPDATE: just found out a moment ago, I'm using kendo ui datasource, I fixed the problem when I removed the Id on the schema
var dataSourceAgenda = new kendo.data.DataSource({
transport: {
type: "odata",
create: {
type: "POST",
url: API_URL + "/agendas",
contentType: "application/json; charset=utf-8",
dataType: 'json'
},
parameterMap: function (options, operation) {
if (operation !== "read" && options) {
return kendo.stringify(options);
}
}
},
schema: {
model: {
id: "Id", //I get my desired output if this is removed
fields: {
MeetingId: { type: "number" },
Title: { type: "string" },
Description: { type: "string" },
Remarks: { type: "string" },
}
},
}
});
HOWEVER I need to the Id parameter in other functions, is there anyway I can do this without removing the Id in kendo datasource.
Changed the Question title!
According the documentation of Kendo UI DataSource (here), add method accepts an Object not an array of Object.
In addition, you use as id a field called Id that is not among the fields of your model.
Try doing the following:
var dataSourceAgenda = new kendo.data.DataSource({
transport: {
create : function (op) {
...
},
parameterMap: function (options, operation) {
if (operation !== "read" && options) {
return kendo.stringify(options.models);
}
}
},
batch : true,
schema : {
model: {
id : "Id", //I get my desired output if this is removed
fields: {
Id : { type: "number" },
MeetingId : { type: "number" },
Title : { type: "string" },
Description: { type: "string" },
Remarks : { type: "string" }
}
}
}
});
I.e.:
Set batch to true for being able to send multiple requests at a time when you invoke sync.
Define Id in the schema.model.fields definition.
Do the stringify of options.models.
As agendaBatch is obviously an array, I assume that kendo.stringify is not serializing it properly. You could go with JSON.stringify.
Note that this is not implemented by older browsers. If you need to support them, you could include the script by Douglas Crockford:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
EDIT
Now that you changed your question - I am not really familiar with kendo ui, so this really is just a wild guess in an attempt to help you with your updated problem.
It looks like you have access to the data in the beforeSend function. You could try to manipulate it for your needs, like this maybe:
beforeSend: function (xhr, s) {
var arrayData = [];
for (var id in s.data) {
arrayData.push(s.data[id]);
}
s.data = arrayData;
}
I am generating a tree in plone using an add-on product called collective.virtualtreecategories . However, I keep getting a weird javascript error and the tree cannot be displayed.
On my browser's error console, I get the following:
$tree.tree is not a function
Here is the part of code that produces the error:
$tree.tree({
data: {
type: "json",
url: "##vtc-categories-tree.json",
async: false
},
lang: {
new_node: "New category"
},
rules: {
deletable: ["folder"],
renameable: ["folder"],
draggable: "none",
droppable: "none",
},
callback: {
beforechange: function(node, tree_obj) {
return before_change_node()
},
onselect: function(node, tree_obj) {
node_selected(node)
},
oncreate: function(node) {
jq(node).attr('rel', 'folder')
},
onrename: function(node, lang, tree_obj, rb) {
old_id = node.id // may be undefined (new node)
new_name = jq(node).children("a:visible").text();
// shared code. Server determines if creating/renaming by the old_name value
jq.ajax({
type: 'POST',
url: "vtc-category-added-renamed",
data: {
'category_path': selected_category(node),
'old_id': old_id,
'new_name': new_name
},
success: function(data) {
jq.jGrowl(data.msg, {
life: 1500
});
// set/change node id
if (data.result) {
node.id = data.new_id
}
},
dataType: 'json',
traditional: true
})
},
beforedelete: function(node, tree_obj) {
jq.ajax({
type: 'POST',
url: "vtc-category-removed",
data: {
'category_path': selected_category(node)
},
success: function(data) {
jq.jGrowl(data.msg, {
life: 3000
});
},
dataType: 'json',
traditional: true
});
return true;
}
}
});
The complete code listing can be found HERE
Can someone help me fix this?
UPDATE:
I should perhaps add that, this was working before in a different setting. Now, I just recreated the project and thats when I got this error.
As far as I can tell from your code $tree isn't a function, its an element
on line 89 var $tree = jq('ul#VTCTree');
therefore I assume .tree() is a JQuery widget and isn't working as expected?
Just seen some of the comments and the updates. Have you checked the path/file inclusion of the tree plugin/widget?
On my browser's error console, I get the following:
if your browser is Internet Explorer, the extra comma that you have here
droppable: "none",
is a widely known problem.
Not a problem for Firefox, but will give unexpected results, like 3 elements in the following array. but length = 4
myArr = [1,2,3,,]
also, check this https://stackoverflow.com/a/5139232/982924
I had the same issue, even though I had jquery loaded and the jquery.filetree.min plugin loaded. I was missing the jquery UI js which is also required.