Get data from php file to javascript - javascript

The javascript below is supposed to be some sort of autocomplete. I am using bootstrap typeahead.
When I type items in my input field, I am able to see suggestions, the problem is I am not able to select them and populate the input field.
Any idea what may be wrong with it?
<script type="text/javascript">
$('#typeahead').typeahead({
source: function (query, process) {
objects = [];
map = {};
return $.get('live_search.php?filter=relation', { query: query }, function (data) {
console.log(data);
var data = $.parseJSON(data);
return process(data);
});
$.each(data, function(i, object) {
map[object.name] = object;
objects.push(object.name);
});
process(objects);
},
updater: function(item) {
$('#getSelection').val(map[item].name);
$('#getValue').val(map[item].name);
return item;
}
});
</script>

It looks like your source method returns immediately from the $.get call and never enters the $.each iteration. Move the iteration code into the get request callback block.
Also you're references to objects and map are in the scope of the source method, but you reference them in the updater method
var typeahead = {
objects: [],
map: {},
};
$("#typeahead").typeahead({
source: function(query, process) {
return $.get("live_search.php?filter=relation", { query: query }, function(
data
) {
var data = $.parseJSON(data);
$.each(data, function(i, object) {
typeahead.map[object.name] = object;
typeahead.objects.push(object.name);
});
return process(data);
});
},
updater: function(item) {
$("#getSelection").val(typeahead.map[item].name);
$("#getValue").val(typeahead.map[item].name);
return item;
},
});

Related

AJAX data in template of Select2

I am populating Select2 with AJAX data. My code is like below.
function formatState(state) {
if (!state.id) { return state.text; }
var output = $('<span></span>'); // I would like get data `text[1]` of `processResults` here.
return output;
};
//more code here
cellEle.html(`<select multiple="multiple"></select>`);
let selectEle = cellEle.children("select").select2({
//more code here
ajax: {
//more code here
processResults: function (data) {
var options = [];
if (data) {
$.each(data, function (index, text) {
options.push({ id: index, text: text[0]});
});
}
return {
results: options,
more: false
};
},
},
templateSelection: formatState,
});
I would like get AJAX data text[1] of processResults inside formatState() of templateSelection.
How can I get it ?
You can pass any extra data via processResults. In your case it can be
var options = [];
if (data) {
$.each(data.items, function (index, text) {
options.push({ id: index, text: text[0], text2: text[1] /* <-- extra data */});
});
}
return {
results: options,
more: false
};
Then access it in templateSelection
if (!state.id) {
return state.text;
}
return $(`<span>${state.text} & ${state.text2}</span>`);
http://jsfiddle.net/moshfeu/3hrupdn1/22/

How to set selected value of typeahead

how can i set a default value in typeahead .
i tried many solutions here, but no one seems to work .
Like tagApi.tagsManager("pushTag", 'deafulttag');
Below is my whole code .
$(document).ready(function() {
var tagApi = $(".tm-input").tagsManager();
jQuery(".typeahead").typeahead({
name: 'job_skill',
displayKey: 'category',
source: function (query, process) {
return $.get('ajaxpro.php', { query: query }, function (data) {
data = $.parseJSON(data);
return process(data);
});
},
afterSelect :function (item){
tagApi.tagsManager("pushTag", item);
}
});
});
Thanks in advance for the help .
You could pre-fill the element with a value?
jQuery(".typeahead").typeahead('val',"test");
Source: Bootstrap typeahead - How to set the default value manually
Edit:
In your example you'd want to initiate typeahead with this value something like below rather than re-initialising it:
$(document).ready(function() {
var tagApi = $(".tm-input").tagsManager();
jQuery(".typeahead").typeahead({
name: 'job_skill',
displayKey: 'category',
val: 'test',
source: function (query, process) {
return $.get('ajaxpro.php', { query: query }, function (data) {
data = $.parseJSON(data);
return process(data);
});
},
afterSelect :function (item){
tagApi.tagsManager("pushTag", item);
}
});
});

Unable to access knockout observable array item

I fetch data from web api and push the data into observable array. I would like to make the observable array item to be observable. However, it seems that i could not access the object if i make it observable.
function KnockoutViewModel() {
var self = this;
self.ProfileList = ko.observableArray([]);
self.GetProfile = function() {
$.ajax({
type: 'GET',
success: function() {
$.each(data.ProfileList, function (index, value) {
self.ProfileList.push(value);
alert(self.ProfileList()[index].Name) // success
}
}
});
}
self.GetProfile();
}
function KnockoutViewModel() {
var self = this;
self.ProfileList = ko.observableArray([]);
self.GetProfile = function() {
$.ajax({
type: 'GET',
success: function() {
$.each(data.ProfileList, function (index, value) {
self.ProfileList.push(ko.observable(value));
alert(self.ProfileList()[index].Name) // fail. Object does not support property or method 'Name'
}
}
});
}
self.GetProfile();
}
you are directly pushing object (by making it observable) into observableArray does it sound right ? Nah (you may want to make Name as observable i believe) . Tough you can get the output by doing something like this self.ProfileList()[index]().Name check here
Preferred way :
viewModel:
function convert(data) {
this.Name = ko.observable(data.Name)
this.place = ko.observable(data.place)
this.age = ko.observable(data.age)
}
function KnockoutViewModel() {
var self = this;
self.ProfileList = ko.observableArray([]);
self.GetProfile = function () {
var data = [{
'Name': 'Super',
'place': 'Ind',
'age': 25
}, {
'Name': 'Cool',
'place': 'Aus',
'age': 15
}]
//Manual way with function defined
//self.ProfileList(ko.utils.arrayMap(data, function (value) {
// return new convert(value)
//}))
//Using Mapping Plugin
ko.mapping.fromJS(data,{},self.ProfileList)
}
self.GetProfile();
}
ko.applyBindings(new KnockoutViewModel());
working sample here
Try to use the mapping module:
self.ProfileList.push(ko.mapping.fromJS(value));
This will automatically wrap value's properties in knockout observables.

Unable to select item in Select2 drop down

I am working on an app that uses Select2 (version 3.5.1). The HTML to setup this drop down / autocomplete field looks like this:
<input id="mySelect" class="form-control" type="hidden">
The form-control class in this snippet comes from Bootstrap. I am initializing this field from JavaScript using the following:
function getItemFormat(item) {
var format = '<div>' + item.ItemName + '</div>';
return format;
}
$(function() {
$('#mySelect').select2({
minimumInputLength: 5,
placeholder: 'Search for an item',
allowClear: true,
ajax: {
url: '/api/getItems',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
query: term
};
},
results: function (data, page) {
return { results: data, id: 'ItemId', text: 'ItemText' };
}
},
formatResult: getItemFormat,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
});
When my select field loads, it successfully renders. Once I type at least the fifth character, it successfully pulls items from the server and lists them as options. However, if I try to select one of them, nothing happens. The drop-down popup stays open. Nothing gets put in the actual field. There are no errors in the JavaScript console. Its like I didn't click anything.
In addition, I noticed that nothing is highlighted when I put my mouse over an item or attempt to navigate the list of options with the arrow keys.
What am I doing wrong?
What is happening:
By default, results of the object you are returning in ajax.results should be an array in this structure [{id:1,text:"a"},{id:2,text:"b"}, ...].
results: function (data, page) {
var array = data.results; //depends on your JSON
return { results: array };
}
In Select2.js it actually states:
* #param options.results a function(remoteData, pageNumber, query) that converts data returned form the remote request to the format expected by Select2.
* The expected format is an object containing the following keys:
* results array of objects that will be used as choices
* more (optional) boolean indicating whether there are more results available
* Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
Reading the source code, we can see that ajax.results is called on AJAX success:
success: function (data) {
// TODO - replace query.page with query so users have access to term, page, etc.
// added query as third paramter to keep backwards compatibility
var results = options.results(data, query.page, query);
query.callback(results);
}
So ajax.results is really just a function for you to format your data into the appropriate structure ( e.g. [{id:a,text:"a"},{id:b,text:"b"}, ...]) before the data is passed to query.callback:
callback: this.bind(function (data) {
// ignore a response if the select2 has been closed before it was received
if (!self.opened()) return;
self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
self.postprocessResults(data, false, false);
if (data.more===true) {
more.detach().appendTo(results).html(self.opts.escapeMarkup(evaluate(self.opts.formatLoadMore, self.opts.element, page+1)));
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
} else {
more.remove();
}
self.positionDropdown();
self.resultsPage = page;
self.context = data.context;
this.opts.element.trigger({ type: "select2-loaded", items: data });
})});
And what query.callback eventually does is to set the logic up properly so that everything works fine when you choose one of the items and trigger .selectChoice.
selectChoice: function (choice) {
var selected = this.container.find(".select2-search-choice-focus");
if (selected.length && choice && choice[0] == selected[0]) {
} else {
if (selected.length) {
this.opts.element.trigger("choice-deselected", selected);
}
selected.removeClass("select2-search-choice-focus");
if (choice && choice.length) {
this.close();
choice.addClass("select2-search-choice-focus");
this.opts.element.trigger("choice-selected", choice);
}
}
}
So if there is some misconfiguration (e.g. results is not in the correct structure) that causes the class .select2-search-choice-focus not to be added to the DOM element before .selectChoice is called, this is what happens:
The drop-down popup stays open. Nothing gets put in the actual field. There are no errors in the JavaScript console. Its like I didn't click anything.
Solutions
There are many solutions to this. One of them is, of course, do some array keys manipulation in ajax.results.
results: function (data, page) {
//data = { results:[{ItemId:1,ItemText:"a"},{ItemId:2,ItemText:"b"}] };
var array = data.results;
var i = 0;
while(i < array.length){
array[i]["id"] = array[i]['ItemId'];
array[i]["text"] = array[i]['ItemText'];
delete array[i]["ItemId"];
delete array[i]["ItemText"];
i++;
}
return { results: array };
}
But you may ask: why must the id be "id" and the text be "text" in the array?
[{id:1,text:"a"},{id:2,text:"b"}]
Can the array be in this structure instead?
[{ItemId:1,ItemText:"a"},{ItemId:2,ItemText:"b"}]
The answer is yes. You just need to overwrite the id and text functions with your own functions.
Here are the original functions for .selecte2 in Select2.js:
id: function (e) { return e == undefined ? null : e.id; },
text: function (e) {
if (e && this.data && this.data.text) {
if ($.isFunction(this.data.text)) {
return this.data.text(e);
} else {
return e[this.data.text];
}
} else {
return e.text;
}
},
To overwrite them, just add your own functions inside the object you are passing to .selecte2:
$('#mySelect').select2({
id: function (item) { return item.ItemId },
text: function (item) { return item.ItemText }
......
});
Updates
What else is happening :
However, the text of the selected item does not appear in the field after the list closes.
This means .selectChoice has been successfully executed. Now the problem lies in .updateSelection. In the source code:
updateSelection: function (data) {
var container=this.selection.find(".select2-chosen"), formatted, cssClass;
this.selection.data("select2-data", data);
container.empty();
if (data !== null) {
formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
}
if (formatted !== undefined) {
container.append(formatted);
}
cssClass=this.opts.formatSelectionCssClass(data, container);
if (cssClass !== undefined) {
container.addClass(cssClass);
}
this.selection.removeClass("select2-default");
if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
this.container.addClass("select2-allowclear");
}
}
From here we can see that, before the corresponding string of text is placed into the input, it would call formatSelection.
formatSelection: function (data, container, escapeMarkup) {
return data ? escapeMarkup(this.text(data)) : undefined;
},
Update: Solution
Previously I thought this.text(data) can be overwritten by having text: funcion(item){ ... } in the parameters, but sadly it doesn't work that way.
Therefore to render the text properly in the field, you should overwrite formatSelection by doing
$('#mySelect').select2({
id: function (item) { return item.ItemId },
formatSelection: function (item) { return item.ItemText }
//......
});
instead of trying to overwrite text (which should supposedly have the same effect but this way of overwriting is not yet supported/implemented in the library)
$('#mySelect').select2({
id: function (item) { return item.ItemId },
text: function (item) { return item.ItemText } //this will not work.
//......
});
The issue you are facing is that select2 wants all your results to have an id property. If they don't you need to initialise with an id function which returns the id from each result.
It will not allow you to select a result unless you satisfy one of these. So in the case of your example :
function getItemFormat(item) {
var format = '<div>' + item.ItemName + '</div>';
return format;
}
$(function() {
$('#mySelect').select2({
minimumInputLength: 5,
placeholder: 'Search for an item',
allowClear: true,
id: function(item) { return item.ItemId; }, /* <-- ADDED FUNCTION */
ajax: {
url: '/api/getItems',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
query: term
};
},
results: function (data, page) {
return { results: data, id: 'ItemId', text: 'ItemText' };
}
},
formatResult: getItemFormat,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
});
You need to provide an ID that returns from your API like #itsmejodie said.
The other problem is that you have to provide select2 formatResult and formatSelection functions, once you have it loaded from Ajax but you can't put html on that. e.g.:
function format (item) {
return item.name;
}
$(function() {
$('#mySelect').select2({
minimumInputLength: 2,
placeholder: 'Search for an item',
allowClear: true,
ajax: {
url: '/api/getItems',
dataType: 'jsonp',
quietMillis: 250,
data: function (term, page) {
return {
query: term
};
},
results: function (data, page) {
return { results: data };
}
},
formatResult: format,
formatSelection: format
});
});
For version 4 of Select2 use
processResults: function (data) {
instead of
results: function (data) {

Dynamically populating Twitter Bootstrap Typeahead

Typeahead works if I give a static array as the source, but when I try to generate the array with function it won't populate its dropdown list.
$("#mix-artist" ).typeahead({
source: function(query, process) {
Mix.searchArtist(query);
},
minLength: 3,
});
The function for the source:
searchArtist: function(query) {
$.get(API_MAIN_URL, {a: "search.artists", q: query},
function(data) {
artists = [];
query = query.toLowerCase();
if (data['aData']) {
for (var i = 0; i <= data['aData'].length; i++) {
if (data['aData'][i] && data['aData'][i]['sName'].toLowerCase().indexOf(query) == 0) {
artists.push(data['aData'][i]['sName']);
}
}
}
console.log(artists);
return artists;
});
}
Sample output of the source function:
["Arcangel", "Arc Angels", "Arcade Fire", "Arctic Monkeys", "Archers of Loaf", "Architecture in Helsinki", "Archie Shepp", "Arcade", "Arch Enemy", "Arcadia", "Archie Eversole"]
What can I do to get typeahead to accept this array?
You need your searchArtist function to take the process callback. Instead of returning the array you should call process(artists).

Categories