jQuery UI Autocomplete With Json Not Showing Suggestions - jquery-ui

I'm experiencing some troubles with an autocomplete component from jQueryUi. The list with autocomplete suggestions doesn't appear.
I've tested the following code (from jQuery UI) and, despite servlet is sending a JSON object and "data" variable is storying it, component is still not showing suggestions list.
Also I tried the component with a simple list as source (like here), and it worked fine.
Have you any idea on what would be happening?
<script>
$(function() {
var cache = {};
$( "#bear" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "/animals/MaintainMamals?operation=14", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
}
});
});
</script>
<form>
<div class="ui-widget">
<label for="bear">Bear name (type a piece of name): </label>
<input id="bear" name="bear" class="text ui-widget-content ui-corner-all"/>
</div>
</form>
Json object used in testing (I tried the stuff with a simple jSon built with just a String refering to "name" property, with the same [bad] results):
[
{
"id": 1234567,
"name": "Yogi Bear",
"activity": {
"handler": {
"interfaces": [
{}
],
"constructed": true,
"persistentClass": {},
"getIdentifierMethod": {
"clazz": {},
"slot": 2,
"name": "getCod",
"returnType": {},
"parameterTypes": [],
"exceptionTypes": [],
"modifiers": 1,
"root": {
"clazz": {},
"slot": 2,
"name": "getId",
"returnType": {},
"parameterTypes": [],
"exceptionTypes": [],
"modifiers": 1,
"override": false
},
"override": false
},
"setIdentifierMethod": {
"clazz": {},
"slot": 3,
"name": "setId",
"returnType": {},
"parameterTypes": [
{}
],
"exceptionTypes": [],
"modifiers": 1,
"root": {
"clazz": {},
"slot": 3,
"name": "setId",
"returnType": {},
"parameterTypes": [
{}
],
"exceptionTypes": [],
"modifiers": 1,
"override": false
},
"override": false
},
"overridesEquals": false,
"entityName": "com.zoo.Activity",
"id": 7105,
"initialized": false,
"readOnly": false,
"unwrap": false
}
}
}
]

The autocomplete widget expects each item in your array to have a label property, a value property, or both. Since your data does not have either, you can either:
Tweak your server-side data source to return items that meet that criteria, or
Transform the data from your server-side code to match the criteria after you make the request.
I can only provide an answer to #2 since I don't see your server-side code, so here's how you would do that:
$(function() {
var cache = {};
$( "#bear" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if (term in cache) {
response(cache[ term ]);
return;
}
$.getJSON("/animals/MaintainMamals?operation=14", request, function (data, status, xhr) {
/* Add a `label` property to each item */
$.each(data, function (_, item) {
item.label = item.name;
});
cache[term] = data;
response(data);
});
}
});
});
Here's an example that fakes an AJAX request--other than that it should be similar to your situation.

Related

Extjs 6.7 TreeList load data infinite from remote store

I try to fill a treelist with remote data via a ajax proxy but the treelist shows only the first level and try to reload the sub levels even though the json response contain a complete tree structure. Fiddle link: https://fiddle.sencha.com/#view/editor&fiddle/33u9
When i try to expand the node 'SUB a' (or set the expanded property to true) the store trys to reload the node.
Why is the tree structure from the json response not honored?
Thanks in Advance.
The backend response looks like:
{
"data": {
"root": [
{
"leaf": true,
"text": "Server"
},
{
"leaf": true,
"text": "Storage"
},
{
"text": "SUB a"
"children": [
{
"leaf": true,
"text": "Modul A - 1"
},
{
"leaf": true,
"text": "Modul A - 2"
}
],
},
{
"leaf": true,
"text": "Modul B"
}
]
},
"success": true
}
The used reader config is
reader: {
type: 'json',
rootProperty: 'data.root',
successProperty: 'data.success',
},
After playing around i use the following workaround:
getNavigation: function() {
var me = this,
tree = me.getView().down('navigationtree'),
store = tree.getStore(),
node = store.getRoot();
Ext.Ajax.request({
url: '/getnav',
method: 'POST',
success: function(response) {
var obj = Ext.decode(response.responseText),
childs = obj.data.root;
tree.suspendEvents();
node.removeAll();
childs.forEach(function(item) {
node.appendChild(item);
});
tree.resumeEvents();
},
failure: function(response) {
//debugger;
console.log('server-side failure with status code ' + response.status);
}
}).then(function() {
//debugger;
}
);
}
The funny things is that only the first level of the tree has to be added all following sub-levels are added automaticaly.

how to get value from json file using jquery autocomplete

This is my jquery code
$('.typeahead', this).autocomplete({
source: function(request, response) {
$.ajax({
url: 'includes/stations.json',
dataType: 'json',
data: request,
success: function(data) {
response($.map(data, function(item, i) {
return {
label: item.name,
value: item.code
}
}));
},
});
},
minLength: 3
});
My Json File is
[
{
"code": "9BP3",
"name": "9Bp No3"
},
{
"code": "AA",
"name": "Ataria"
},{
"code": "BILA",
"name": "Bheslana"
},
{
"code": "BILD",
"name": "Bildi"
},{
"code": "HRI",
"name": "Hardoi"
},
{
"code": "HRM",
"name": "Hadmadiya"
}
]
When i typing any three letter its returns whole json file values
q: request.term this is the string for filter returned values from stations.json. You must pass variable like this to filter results. stations.json must be dynamically generated file like php with json header. q is $_GET parameter and must be parsed. Try to change the code like this:
$.ajax({
url: "includes/stations.json",
dataType: "json",
data: {
q: request.term // here is the string for filter returned values from stations.json. You must pass variable like this to filter results. stations.json must be dynamically generated file like php with json header. q is $_GET parameter and must be parsed.
},
success: function(data) {
response(
$.map(data, function(item, i) {
return {
label: item.name,
value: item.code
}
})
);
}
});
},
minLength: 3,

Knockoutjs one to many mapping not working

In this following code snippet I am creating parent child view model using knockoutjs mapping plugin.I am not getting any error in mapping But when I am running the application it's throwing the error name is not defined.
data = {
"Id": 1,
"Name": "Microsoft",
"Address": "USA",
"WebPage": "SS",
"Employees": [
{
"Id": 1,
"FirstName": "sadsasa",
"LastName": "ADF",
"Twitter": "dfd",
"WebPage": "sdfdf"
},
{
"Id": 2,
"FirstName": "sadsasa",
"LastName": "ADF",
"Twitter": "dfd",
"WebPage": "sdfs"
},
{
"Id": 3,
"FirstName": "sadsasa",
"LastName": "ADF",
"Twitter": "dfd",
"WebPage": "sfdfs"
}
]
};
var mapping = {
'Employees': {
create: function (options) {
alert(options);
return new PersonViewModel(options.data);
}
}
}
function PersonViewModel(data) {
ko.mapping.fromJS(data);
}
function CompanyViewModel(data) {
ko.mapping.fromJS(data, mapping, this);
}
var company;
$(document).ready(function () {
$.ajax({
url: '/api/Greet',
type: 'GET',
dataType: 'json',
success: function (result) {
data = JSON.stringify(result);
company = new CompanyViewModel(data);
console.log(company);
ko.applyBindings(company);
},
error: function (e) {
alert(e);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
FirstName: <span data-bind="text:Name"></span>
</div>
Well you need to do some small modifications in your code .
View Model :
function PersonViewModel(data) {
ko.mapping.fromJS(data,mapping,this);
}
function CompanyViewModel(data) {
self.childlist=ko.observableArray();
ko.mapping.fromJS(data, mapping, this);
self.childlist.push(new PersonViewModel()); //child array
}
View :
<div>
<b>FirstName:</b> <span data-bind="text:Name"></span>
<div data-bind="foreach:Employees">
<span data-bind="text:Id"></span>
</div>
</div>
Working fiddle here
Do let me know incase of any issues .

How do get an Ember.Select to be populated via Rails backend data?

I'm trying to write a select box in Ember, based on a Rails back end. When editing the model Recipes, I want to be able to select from a list of Sources in a dropdown. Right now in Ember I'm getting the message "The value that #each loops over must be an Array. You passed App.Sources" as a result of the following code.
I have tested the REST api and it is providing the response for Recipes and Sources both properly.
I'm new to Embers (and Javascript too, actually!) and I feel like I'm missing something basic. Thank you for any tips.
Here's my JS:
App.RecipeEditController = Ember.ObjectController.extend({
needs: ['sources'],
selectedSource: null,
actions: {
save: function() {
var recipe = this.get('model');
// this will tell Ember-Data to save/persist the new record
recipe.save();
// then transition to the current recipe
this.transitionToRoute('recipe', recipe);
}
}
});
App.RecipesRoute = Ember.Route.extend({
model: function() {
return this.store.find('recipe');
},
setupController: function(controller, model) {
this._super(controller, model);
this.controllerFor('sources').set('content', this.store.find('source'));
}
});
App.SourcesRoute = Ember.Route.extend({
model: function() {
return this.store.find('source');
}
});
DS.RESTAdapter.reopen({
namespace: "api/v1"
});
App.Recipe = DS.Model.extend({
title: DS.attr('string'),
url: DS.attr('string'),
rating: DS.attr('number'),
source: DS.belongsTo('source', {
async: true
}),
page_number: DS.attr('number'),
want_to_make: DS.attr('boolean'),
favorite: DS.attr('boolean')
});
App.Source = DS.Model.extend({
title: DS.attr('string'),
authorLast: DS.attr('string'),
recipes: DS.hasMany('recipe', {
async: true
})
});
App.Router.map(function() {
return this.resource("recipes");
});
App.Router.map(function() {
return this.resource("recipe", {
path: "recipes/:recipe_id"
});
});
App.Router.map(function() {
return this.resource("recipeEdit", {
path: "recipes/:recipe_id/edit"
});
});
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.RESTAdapter
});
And here's the view:
{{view Ember.Select
contentBinding="controllers.sources.content"
optionLabelPath="content.title"
optionValuePath="content.id"}}
UPDATE And here's the JSON:
{
"recipes": [
{
"id": 3,
"title": "Did this make it through?",
"url": "www.hellyeahitdid.com/high-five/",
"rating": null,
"source_id": null,
"page_number": null,
"want_to_make": false,
"favorite": false
},
{
"id": 1,
"title": "Here's another totally crazy one for ya",
"url": "http://www.example.com/recipe/1",
"rating": null,
"source_id": null,
"page_number": null,
"want_to_make": false,
"favorite": false
},
{
"id": 2,
"title": "A Sample Recipe",
"url": "http://www.example.com/recipe/1",
"rating": null,
"source_id": null,
"page_number": null,
"want_to_make": false,
"favorite": false
}
]
}
{
"sources": [
{
"id": 1,
"title": "Joy of Cooking",
"author_last": null
},
{
"id": 2,
"title": "Everyday Food",
"author_last": null
}
]
}
Welcome to javacript/ember, here's an example using a select.
http://emberjs.jsbin.com/OxIDiVU/69/edit
you'll notice the i don't quote real properties, and do quote strings
{{ view Ember.Select
content=someSource
optionValuePath='content.id'
optionLabelPath='content.title'
}}
Additionally that appears to be a very old version of Ember Data. You may consider updating. https://github.com/emberjs/data/blob/master/TRANSITION.md
Your routing can go in a single call
App.Router.map(function() {
this.resource("recipes");
this.resource("recipe", { path: "recipes/:recipe_id"}, function(){
this.route('edit');
});
});
This should get you started
http://emberjs.jsbin.com/OxIDiVU/74/edit

Google Linecharts json data source?

I use google line chart but I cant success to assing source to chart.
script
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: '#Url.Action("AylikOkumalar", "Enerji")',
dataType: "json",
async: false
}).responseText;
var rows = new google.visualization.DataTable(jsonData);
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'T1');
data.addColumn('number', 'T2');
data.addColumn('number', 'T3');
data.addRows(rows);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div')).draw(data, { curveType: "function",
width: 700, height: 400,
vAxis: { maxValue: 10 }
}
);
}
</script>
action
public ActionResult AylikOkumalar()
{
IEnumerable<TblSayacOkumalari> sayac_okumalari = entity.TblSayacOkumalari;
var sonuc = sayac_okumalari.Select(x => new
{
okuma_tarihi = ((DateTime)x.okuma_tarihi).ToShortDateString(),
T1 = (int)x.toplam_kullanim_T1,
T2 = (int)x.toplam_kullanim_T2,
T3 = (int)x.toplam_kullanim_T3
});
return Json(sonuc, JsonRequestBehavior.AllowGet);
}
json output
and script error:
Argument given to addRows must be either a number or an array.
I use it first time. So I dont know what should I do. How can use charts with mvc 3. there is no example enough.
Thanks.
data.addRows(rows);
'rows' should be an array - something like :
data.addRows([
[new Date(1977,2,28)], 1, 2, 3],
[new Date(1977,2,28)], 1, 2, 3]
]);
or your jsonData could be instead the whole structure :
{
"cols": [
{"id": "", "label": "Date", "type": "date"},
{"id": "", "label": "T1", "type": "number"}
],
"rows": [
{"c":[{"v": "Apr 24th"}, {"v": 56000} ]},
{"c":[{"v": "May 3rd" }, {"v": 68000} ]}
]
}

Resources