Handling Remote Data (Table Data - Undefined) - json

following the documentation here
I have my own web service with JSON data just for testing purposes here
Ti.API.info('Received text: ' + this.responseText); shows the JSON in console, but when i try display in table I get undefined?
The documentation example uses json.figters.length --- i used json.places.length, as it is the name on array list on my web application.
var win = Ti.UI.createWindow();
var table = Ti.UI.createTableView();
var tableData = [];
var json, places, place, i, row, countryLabel, capitalLabel;
var xhr = Ti.Network.createHTTPClient({
onload : function(){
Ti.API.info('Received text: ' + this.responseText);
json = JSON.parse(this.responseText);
for (i=0; i < json.places.length; i++)
{
place = json.places[i];
row = Ti.UI.createTableViewRow({
height: '60dp'
});
countryLabel = Ti.UI.createLabel({
text: place.country,
font:{
fontSize:'24dp'
},
height: 'auto',
left: '10dp',
top: '5dp',
color: '#000',
touchEnabled:false
});
capitalLabel = Ti.UI.createLabel({
text:'"' + place.captial + '"',
font:{
fontSize:'16dp'
},
height: 'auto',
left: '15dp',
top: '5dp',
color: '#000',
touchEnabled:false
});
row.add(countryLabel);
row.add(capitalLabel);
tableData.push(row);
}//end for
table.setData(tableData);
},
onerror: function() {
Ti.API.info('error, HTTP status = ' + this.status);
alert('Error Reading Data');
},
timeout:5000
});
xhr.open("GET", "http://130.206.127.43:8080/Test");
xhr.send();
win.add(table);
win.open();

you're pushing 2 labels into a row, but a row does not have a wrapper view.
Try something like this:
var rowView Ti.UI.createView({height: 60, layout: 'horizontal'});
rowView.add(countryLabel);
rowView.add(capitalLabel);
row.add(rowView);
tableData.push(row);

Related

Adding slides to Slick with ajax

so I'm using Slick Carousel and I'm showing in it a list of products from my database limited to 24 for performance reasons. But I need to show all of them, so I made a afterChange function that ajax loads another 24 products everytime the user is 2 slides before the end and add them with slickAdd function to the end of the Slick.
Everything is working fine but when the slickAdd function executes, the slides width changes for some reason from 457px to 451px and I can see a part of the 4th slide on the current slide.(I have 3 shown) Then if I click on the next button again, the width goes back to 457px and everything is ok.
$('.demo').slick({
slidesToShow: 3,
slidesToScroll: 3,
infinite: false,
});
$('.demo').on('afterChange', function(event, slick, currentSlide, nextSlide){
var komponent = $(".komponent-container.active").attr("id");
var loadWhen = currentSlide+6;
if(loadWhen == slick.slideCount){
console.log("loadmore");
$.ajax({
type: "POST",
url: "/project/public/konfigurator",
data: {id: komponent, from_column: slick.slideCount, requestid: "load_more"},
dataType: "json",
success: function (data) {
var data_parser = JSON.parse(data)[0];
if (data_parser.length > 0) {
var html = '';
for (i = 0; i < data_parser.length; i++) {
var produkt_nazov = 0;
if (data_parser[i].produkt.length > 45) {
produkt_nazov = data_parser[i].produkt.substring(0, 45) + "...";
} else {
produkt_nazov = data_parser[i].produkt;
}
html += '<div><div class="item-container"><div class="container-wrapper"><div class="produkt-container"><div class="item-left"><div class="item-image-wrapper"><img draggable="false" id="produkt-img" src="img/konfigurator/'+komponent+'/' + data_parser[i].produkt + '/1.jpg" alt="" /></div><div class="cena">' + data_parser[i].cena + ' €</div></div><div class="item-right"><div class="item-info"><span class="item-title">' + produkt_nazov + '</span><span class="item-description"><span>Výrobca čipu - ' + data_parser[i].vyrobca_cipu + '</span><span>Veľkosť pamäte - ' + data_parser[i].vram_size + '</span><span>Typ pamäte - ' + data_parser[i].vram_type + '</span><span>Frekvencia jadra - ' + data_parser[i].gpu_memory_clockrate + '</span></span></div><div class="spodna-cast"><div class="action-buttons"><a class="detail-button">Detail</a><a class="add-button">Vybrať</a></div></div></div></div></div></div></div>';
}
$(".demo").slick('slickAdd', html);
console.log("add");
}
},
error: function (result) {
alert('error');
}
});
}
});
});
What could be causing this and how to prevent it?
This fixed it for me
$(".demo")[0].slick.setPosition();

Alexa (Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined')

My code is not working when I test it in Amazon Developer and I don't see anything wrong with my code. It says my response is invalid.
Here's the code I tried to run but failed(I ran one response but not the other):
var Alexa = require('alexa-sdk');
exports.handler = function(event, context, callback) {
var alexa = Alexa.handler(event, context);
// alexa.dynamoDBTableName = 'YourTableName'; // creates new table for userid:session.attributes
alexa.registerHandlers(handlers);
alexa.execute();
};
var handlers = {
'LaunchRequest': function () {
this.emit('WelcomeIntent');
},
'WelcomeIntent': function () {
this.emit(':ask', 'Welcome to the guessing game! What difficulty would you like to play? Easy, Medium, or Hard?');
},
//------------------------------------------------------------------------------------------------------------------------------------------------
'DifficultyIntent': function (){
var difficulty = this.event.request.intent.slots.difficulty.value;
var range = 10; this.attributes['RandomNumberEnd'] = range;
if (difficulty === 'easy')
{ range = 10;
this.emit[':ask Your range is 1 - ' + range]
}
else if (difficulty === 'medium')
{ range = 100;
this.emit[':ask Your range is 1 - ' + range]
}
else (difficulty === 'hard');
{ range = 1000;
this.emit[':ask Your range is 1 - ' + range]
}
var randomNumber = Math.floor((Math.random()*range)+1);
var rightAnswer = this.attributes['rightAnswer'] = rightAnswer;
}, //check the user's guess with the right answer
'UserGuessIntent': function (){
var guess = this.event.request.intent.slots.guess.value;
this.attributes['guess'] = guess;
this.emit('CheckIntent'); },
'CheckIntent': function (){
var guess = this.attributes['guess'];
this.attributes['rightAnswer'] = randomNumber;
if(guess < rightAnswer){
this.emit(':ask', 'Try Again! Guess higher!');
}
else if(guess > rightAnswer)
{this.emit(':ask', 'Try Again! Guess lower!');
}
else{
this.emit(':tell', 'You are correct! Congratulations!');
}
},
'QuitIntent': function(){
var stop = this.event.request.intent.slots.stop.value;
this.emit('AMAZON.StopIntent');
},
'AMAZON.StopIntent' : function(){
var rightAnswer = this.attributes['rightAnswer'];
this.emit(':tell', 'The right answer is ' + rightAnswer + '. Goodbye!');
}
};

Unable to format JSON from WCF for HighCharts?

My WCF returns this JSON and i want to bind to HighCharts Pie
Original from WCF -[{"AllRecordsUrl":"http:\/\/EMS\/sites\/IST\/report.aspx","EMSCenterName":"IST","EMSCenterUrl":"http:\/\/EMS\/sites\/IST","Count":2},{"AllRecordsUrl":"http:\/\/EMS\/sites\/LSS\/report.aspx","EMSCenterName":"LSS","EMSCenterUrl":"http:\/\/EMS\/sites\/LSS","Count":17}]
If i hardCode it in cart series as data: [....] it works but the dynamic proccesed data does not..
After processing - [{name: 'IST' , url: 'http://EMS/sites/IST/report.aspx' , y: 2 },{name: 'LSS' , url: 'http://EMS/sites/LSS/report.aspx' , y: 16 }]
Even after processing it to what i showed above highcharts Pie won't work with my data..
I am not sure what is wrong here, would appreciate some guidance
Here's what is done so far ...
function getDataForHub(json) {
var realArray = $.makeArray(json);
//debugger;
//console.log(JSON.stringify(realArray));
var obj = $.parseJSON(JSON.stringify(realArray));
var chartData = [];
$.each(realArray, function (index, item) {
var final;
var element;
var sB = '';
var name = '';
var url = '';
var y = '';
var color = '';
for (element in item) {
if (element == 'EMSCenterName') {
name = 'name' + ": " + "'" + item[element] + "'";
}
if (element == 'AllRecordsUrl') {
url = 'url' + ": " + "'" + item[element] + "'";
}
if (element == 'Count') {
y = 'y' + ": " + item[element];
}
}
sB = name + ' , ' + url + ' , ' + y ;
//console.log(sB);
var elements = [];
//adding each to an array before being pushed to th final array,
elements.push(sB);
chartData.push(elements);
});
return chartData;
}
And here is my Pie
$(function () {
LoadSodByKey("sp.ui.dialog.js", null);
var stdWidth = 530;
var stdHeight = 200;
Highcharts.setOptions({
colors: ['#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
$('#containerpie').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: true,
height: stdHeight + 120,
width: stdWidth + stdHeight
},
title: {
text: 'Records per Program'
},
tooltip: {
pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
/*formatter: function () {
return '<b>' + this.point.name;
}*/
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
},
showInLegend: false
}
},
series: [{
type: 'pie',
size: stdHeight,
data:[{name: 'IST' , url: 'http://EMS/sites/IST/report.aspx' , y: 2 },{name: 'LSS' , url: 'http://EMS/sites/LSS/report.aspx' , y: 16 }],
point: {
events: {
click: function(e) {
//alert(e.point.url);
var options = {
url: e.point.url,
title: e.point.name,
allowMaximize: true,
showClose: true,
width: 1100,
height: 500,
dialogReturnValueCallback: function (result, returnValue) {
//location.reload(true);
}
}
SP.UI.ModalDialog.showModalDialog(options);
e.preventDefault();
}
}
}
}]
});
var data = GetData();});
function GetData(){
var chart = $('#containerpie').highcharts();
series = chart.series[0];
//Ajax call to WCF service
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
crossDomain: false,
url: 'http://EMS/_vti_bin/EMSDashboard.svc/GetEMSCenterDataForHub',
data: null,
dataType: 'json',
success: function (response) {
var dynamicData = getDataForHub(response);
//this doesnot work
//series.data = dynamicData;
//even this does not work
//series.data.push(dynamicData)
//Wrong, wrong, wrong
//series.data.push(eval('[' +dynamicData +']'));
//gives me count of two but the chart does not load wiht dynamic data
console.log(series.data.length);
},
error: function (message) {
alert(message.statusText);
}
});
}
Thanx
FIXED:
Here's how
mistake = I had set up a static chart and was trying to use the same with $AJAX call where the chart was already created without the "data" being created, instead now the "data" array is created first and then the chart is created using chart = new Highcharts.Chart({....})
Also removed all client side preprocessing of the JSON received from WCF i.e my server object has additional Properties for Highchart rendering such to get ..
[{"name":"IST","url":"http:\/\/<XXXX>\/sites\/IST\/ASASA.aspx","y":2},
{"name":"LASS","url":"http:\/\/<XXXX>\/sites\/LASS\/ASASA.aspx","y":17}]

Dynamically generated buttons and pass variable to new window with JSON

First I am a beginner and this is my first app. I have been working on this app for several days and I am stuck. On the page remote_read-org-3.js I am creating buttons that are a list of states. These are being pulled from a mySQL database. This part is working. I need to pass the stateabbr to the next window when the button is clicked. The problem is it passes the last state in the list no matter which button I click.
This is remote_read-org.js It may not been the cleanest code but I am still working through the how to's
var currentWin = Ti.UI.currentWindow;
var view02 = Titanium.UI.createView({
top:0,
left:0,
height: '100%',
width: '100%',
backgroundImage: 'images/wcs_background_2.jpg',
})
var label01 = Titanium.UI.createLabel({
text: "US STATES",
top:25,
left:125,
height:'auto',
width:'175',
textAlign: "left",
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:24},
color: "#1c1e3b",
})
var label02 = Titanium.UI.createLabel({
text: "Attachments",
top:50,
left: 125,
height:'24',
width:'150',
textAlign: "left",
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:18},
color: "#1c1e3b",
})
var view01 = Titanium.UI.createView({
top:90,
left:70,
height: 375,
width: Ti.UI.FILL,
})
var currentWin = Ti.UI.currentWindow;
var sendit = Ti.Network.createHTTPClient();
sendit.open('GET', 'http://localhost/test/read.php');
sendit.send();
sendit.onload = function(){
var json = JSON.parse(this.responseText);
var json = json.states;
var dataArray = [];
var scroller = Ti.UI.createScrollView({
height: Ti.UI.FILL,
width: Ti.UI.FILL,
});
var brandView = Ti.UI.createView({ //Primary view for buttons
title: 'Hello',
top:0,
left:0,
height : Ti.UI.FILL,
width : Ti.UI.FILL,
contentHeight : "auto",
backgroundColor : "transparent",
layout : "horizontal",
horizontalBounce :false,
});
scroller.add(brandView);
view01.add(scroller);
var pos;
for( pos=0; pos < json.length; pos++){
dataArray.push({title:'' + json[pos].stateAbbr + ''});
// set the array to the tableView
var btn = Ti.UI.createButton({
title: json[pos].stateAbbr,
width: 60,
height: 70,
top: pos * 0, // space the buttons at 105
left: 2,
backgroundImage: 'images/state_icon.png',
MyID: json[pos].stateAbbr,
});
btn.addEventListener('click', function(e) {
var newWindow = Titanium.UI.createWindow({
url: 'remote_read_acc.js',
MyID: btn.MyID
});
newWindow.open(newWindow);
});
brandView.add(btn);
};
};
var brandView = Ti.UI.createView({
});
view02.add(view01);
view02.add(label01);
view02.add(label02);
currentWin.add(view02);
I need to pass the stateabbr to this new window
remote_read_acc.js
var currentWin = Ti.UI.currentWindow;
var view02 = Titanium.UI.createView({
top:0,
left:0,
height: '100%',
width: '100%',
backgroundImage: 'images/wcs_background_2.jpg',
})
var label01 = Titanium.UI.createLabel({
text: "US STATES",
top:25,
left:125,
height:'auto',
width:'175',
textAlign: "left",
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:24},
color: "#1c1e3b",
})
var label02 = Titanium.UI.createLabel({
text: "Attachments",
top:50,
left: 125,
height:'24',
width:'150',
textAlign: "left",
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:18},
color: "#1c1e3b",
})
var view01 = Titanium.UI.createView({
top:90,
left:90,
height: 375,
width: Ti.UI.FILL,
})
var currentWin = Ti.UI.currentWindow;
var sendit = Ti.Network.createHTTPClient();
sendit.open('GET', 'http://localhost/test/attachments.php');
sendit.send();
sendit.onload = function(){
var json = JSON.parse(this.responseText);
var json = json.attachments;
var dataArray = [];
var scroller = Ti.UI.createScrollView({
height: Ti.UI.FILL,
width: Ti.UI.FILL,
});
var brandView = Ti.UI.createView({ //Primary view for buttons
title: 'Hello',
top:0,
left:0,
height : Ti.UI.FILL,
width : Ti.UI.FILL,
contentHeight : "auto",
backgroundColor : "transparent",
layout : "horizontal",
horizontalBounce :false,
});
scroller.add(brandView);
view01.add(scroller);
var pos;
for( pos=0; pos < json.length; pos++){
dataArray.push({title:'' + json[pos].attachmentName + ''});
// set the array to the tableView
var btn = Ti.UI.createButton({
title: json[pos].attachmentName ,
width: 190,
height: 30,
top: pos * 0, // space the buttons at 105
left: 2,
MyID: json[pos].attachmentName,
});
btn.addEventListener('click', function(e) {
var newWindow = Titanium.UI.createWindow({
url: '',
});
newWindow.open(newWindow);
brandView.add(btn);
};
};
var brandView = Ti.UI.createView({
});
view02.add(view01);
view02.add(label01);
view02.add(label02);
currentWin.add(view02);
I also then need to use that stateabbr that I passed to query the dataArray to pull just the values from the array that matches the stateabbr variable. so I can display them on this page.
Any help would be greatly appreciated
It's passing the last state in the list cause you are adding event listeners in a for loop and ignoring JavaScript scope rules (they are not the easiest to understand that's for sure). So what is happening is that btn is always equal to the last btn you create. Instead try this, use the source attribute of every click event, this separates your inner scope from the outer scope of the for loop:
btn.addEventListener('click', function(e) {
var newWindow = Titanium.UI.createWindow({
url: 'remote_read_acc.js',
MyID: e.source.MyID // Get the actual button that was clicked
});
newWindow.open(newWindow);
});
To optimize this even further I would move the event listener function outside of the loop. Also, I wouldn't use the url attribute of the window, as that will open an entirely different JavaScript context, which is pretty heavyweight, instead try to use the require() CommonJS directive.

Parse json from bandsintown API

I have trouble to parse and show events from Bands in Town´s API in my appcelerator mobile app. (iOS)
This is my bands event that i want to show in a table.
http://api.bandsintown.com/artists/Lucy%20Seven/events.json?api_version=2.0&app_id=LucySeven
And this is the code that i have for showing it
var win = Ti.UI.currentWindow;
win.hideNavBar();
Ti.UI.backgroundColor = '#050505';
var url = "http://api.bandsintown.com/artists/Lucy%20Seven/events.json? api_version=2.0&app_id=LucySeven"
var table = Ti.UI.createTableView({
backgroundColor: '#050505',
separatorColor:'#110000',
});
var tableData = [];
var json, artists, name, picture, title, description;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
// Ti.API.debug(this.responseText);
json = JSON.parse(this.responseText);
for (i = 0; i < json.data.length; i++) {
data = json.data[i];
row = Ti.UI.createTableViewRow({
height:'100dp',
backgroundColor: '#050505',
separatorColor:'#110000',
});
var name = Ti.UI.createLabel({
text: title,
font:{
fontSize:'17dp',
fontWeight:'bold'
},
height:'auto',
left:'90dp',
top:'20dp',
color:'#eee',
touchEnabled:true
});
row.add(name);
var start = Ti.UI.createLabel({
text: description,
font:{
fontSize:'12dp'
},
height:'auto',
left:'90dp',
bottom:'20dp',
color:'#eee',
touchEnabled:true
});
row.add(start);
// Avatar
var img = Ti.UI.createImageView({
image : thumb_url ,
width : 70,
height : 70,
top : 5,
bottom : 5,
borderRadius: 5,
borderColor: '#eee',
left : 5
});
row.add(img);
tableData.push(row);
}
table.setData(tableData);
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout:5000
});
xhr.open("GET", url);
xhr.send();
There is a API responses for json here:
http://www.bandsintown.com/api/responses#events-json
I really cant see what is wrong... Maybe im to blind to see what i have missed?
I would appreciate if someone could point me in the right direction on this.
i have tried with: data.title data.artists.title title artists.titel and so on but nothing have shown up in my tableview.....
Thanx
//R
What's the value of this.responseText and what's the value of json after JSON.parse? In the JSON response I don't see a data property so I'm not sure what json.data is supposed to be. Also in Ti.UI.createLabel you give test: title but title is never given a value.
I suspect what you really want in your for loop is this:
json = JSON.parse( this.responseText ); // `json` will be an array of objects
for (i = 0; i < json.length; i++) {
data = json[ i ];
// ...
var name = Ti.UI.createLabel( {
text: data.title,
// ...
} );
}
The key to debugging this is the same as debugging many things—find out what data you have at each step (I've never used Titanium but it must have something like console.log at the very least) and figure out how it differs from what you expect.