I use Javascript. I want to get RSS data by API google (this link: http://www.javascriptkit.com/dhtmltutors/googleajaxfeed.shtml ), then insert the data into a Array (Global variable). But my global variable can not save data.
Inside rssfeedsetup() function, ARR_DATA (Global Array) have data. However, after load rssfeedsetup() function, ARR_DATA have no data.
Please show me, how to insert data to global variable in this case.
My code:
Head:
<head>
<title>TEST API FEED RSS</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("feeds", "1"); //Load Google Ajax Feed API (version 1)
</script>
</head>
Body:
<body>
<div id="feeddiv"></div>
<script type="text/javascript">
var ARR_DATA = []; // **I want to insert data into this array**
var feedurl = "http://rss.slashdot.org/Slashdot/slashdot";
var feedlimit = 4;
function rssfeedsetup() {
var feedpointer = new google.feeds.Feed(feedurl); //Google Feed API method
feedpointer.setNumEntries(feedlimit); //Google Feed API method
feedpointer.load(displayfeed); //Google Feed API method
}
function displayfeed(result) {
if (!result.error) {
var thefeeds = result.feed.entries;
var arr_Temporary = [];
for (var i = 0; i < thefeeds.length; i++) {
arr_Temporary[0] = thefeeds[i].title;
arr_Temporary[1] = thefeeds[i].link;
// insert RSS data into ARR_DATA.
ARR_DATA.push(arr_Temporary);
console.log('value before:', ARR_DATA); // check value of ARR_DATA, there have data exist.
}
}
}
window.onload = function () {
rssfeedsetup(); // call function
console.log('value2 after:', ARR_DATA); // check value of ARR_DATA, there is no data.
};
console.log('value2 after:', ARR_DATA); //check value of ARR_DATA, there is no data.
</script>
</body>
I have got value console:
image of firebug on firefox
Ps: Why ARR_DATA no contain data after load function rssfeedsetup()?
You can push data into the array like this:
function displayfeed(result) {
if (!result.error) {
var thefeeds = result.feed.entries;
for (var i = 0; i < thefeeds.length; i++) {
var feed = {
title: thefeeds[i].title,
link: thefeeds[i].link
};
ARR_DATA.push(feed);
}
console.log(feed);
}
}
Hope it helps
Related
My application makes api calls to the census and uses that data in combination with Google Maps API v3. It works as expected much of the time, but I’m getting an intermittent error of ‘Initmap is not defined’, or ‘google is not defined’, or ‘TypeError: map.data.getFeatureById(...) is undefined’ without any discernible reason.
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3&key=KEY1234&callback=initMap" async defer
></script>
<script src="js/mapfunc.js"></script>
</head>
<body>
<div id="map"></div>
<script>var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 35, lng: -106}
});
}</script>
</body>
</html>
JS:
function loadMapShapes() {
map.data.loadGeoJson('jsonya2.geojson', { idPropertyName: 'STATE' });
variable = 'B01003_001E,NAME';
variable2 = ',B01001F_002E';
loadCensusData(variable);
}
function loadCensusData(variable) {
// load the requested variable from the census API
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.census.gov/data/2014/acs5/?get=' +
variable + '&for=state:*&key=KEY123');
xhr.onload = function() {
var censusData = JSON.parse(xhr.responseText);
censusData.shift(); // the first row contains column names
censusData.forEach(function(row) {
censusMin = 0;
censusMax = 36000000;
var censusVariable = parseFloat(row[0]);
var stateName = row[1];
var stateId = row[2];
// keep track of min and max values
if (censusVariable < censusMin) {
censusMin = censusVariable;
}
if (censusVariable > censusMax) {
censusMax = censusVariable;
}
// update the existing row with the new data
coolid = map.data.getFeatureById(stateId);// <-- Here's where
//I get the error most often: "TypeError: map.data.getFeatureById(...) is undefined"
if (coolid !== undefined) {
map.data
.getFeatureById(stateId)
.setProperty('census_variable', censusVariable);
map.data
.getFeatureById(stateId)
.setProperty('census_variable1', stateName);
}
coolstate = map.data.getFeatureById(stateName);
});
Again - this code works maybe 40% of the time, and throws one of the above-described errors the rest of the time. I may notice an increase in errors during the day but can't be sure.
Thanks a lot for any thoughts, here's a link to a live version of this code with census and google maps API calls:
http://dukecitydigital.com/c1/
loadGeoJson runs asynchronously, use the callback of loadGeoJson to execute further functions which depend on the result of loadGeoJson:
function loadMapShapes() {
variable = 'B01003_001E,NAME';
variable2 = ',B01001F_002E';
map.data.loadGeoJson('jsonya2.geojson', { idPropertyName:'STATE'}, function(){
loadCensusData(variable);
});
}
Here is the code I am using to avoid 'undefined' error:
// update the existing row with the new data
if (typeof(map.data.getFeatureById(stateId)) != "undefined") {
map.data
.getFeatureById(stateId)
.setProperty('census_variable', censusVariable);
}
I have the following data in a JSON file (pio2.json)
{
"controles":[{
"chart":[{
"type":"columns",
"title":"Pollitos"
}],
"datos":[{"key":"Math","value":98},
{"key":"Physics","value":78},
{"key":"Biology","value":70},
{"key":"Chemistry","value":90},
{"key":"Literature","value":79}
]
}]
}
I need to extract data in array for a chart from "datos" for my html / javascript
$(function () {
var processed_json = new Array();
$.getJSON('pio2.json', function(data)
{
// Populate series
for (i = 0; i < data.controles.length; i++){
processed_json.push(data.controles[i].chart);
}
}
}
Any advice?
not sure what your issue is. I should be serialized server side and deserialized client side. When deserialized, it will be in an array.
I copied your data, as is, into json1.json pasted in your code and made some minor changes and it worked fine. I got the results out of the json page into my html page.
<body>
<script type="text/javascript">
$(document).ready(function () {
var processed_json = new Array();
$.getJSON('json1.json', function(data)
{
// Populate series
for (i = 0; i < data.controles.length; i++){
processed_json.push(data.controles[i].chart);
}
})
});
</script>
</body>
I want to return a datatable I created in google apps script with data from a Spreadsheet to the client. I use a succesHandler to get the data and use this to create a chart. The only problem i have is that my data is null. It seems i can't return a datatable object to the client page.
I need to send it to the client, because Google Apps script is deprecating the UIApp functions so i need the google.visualization functions in the Client.
Code.gs
function doGet() { return HtmlService.createHtmlOutputFromFile('Index.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);}
function getDataTable()
{
var bestanden = DriveApp.searchFiles('title contains "' + "kwalrap" + '"');
while (bestanden.hasNext())
{
var bestand = bestanden.next();
var docid = ( bestand.getId() );
Logger.log(docid);
};
var sheets= SpreadsheetApp.openById(docid).getSheets();
//vanaf sheet 0. tot hij bij de laatset sheet is. dan steeds 2 sheets verder.
for(var j = 0; j < 2; j = j+1)
{
var sheet = sheets[j];
//Logger.log(sheet.getSheetName());
var range = sheet.getRange(2,1,sheet.getLastRow(),8);
var inforange = sheet.getRange(2,1,1,8);
var values = range.getValues();
var infovalues = inforange.getValues();
var data = Charts.newDataTable()
.addColumn(Charts.ColumnType.STRING, "Tijd")
.addColumn(Charts.ColumnType.NUMBER, "dco")
.addColumn(Charts.ColumnType.NUMBER, "dcp")
.addColumn(Charts.ColumnType.NUMBER, "dct")
.addColumn(Charts.ColumnType.NUMBER, "dcz")
.addColumn(Charts.ColumnType.NUMBER, "ldc")
.addColumn(Charts.ColumnType.NUMBER, "lv")
for(var i = 0; i < sheet.getLastRow()-1; i++)
{
data.addRow([values[i][0],values[i][1],values[i][2],values[i][3],values[i][4],values[i][5],values[i][6]]);
Logger.log(values[i]);
}
var dataTable = data.build();
return dataTable;
// return JSON.stringify(values);
}
}
Index.html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function onSuccess(data) {
var options = {
title: 'Why doesn't this work'
};
new google.visualization.LineChart(
document.getElementById('visualization_div')).draw(data, options);
}
google.script.run.withSuccessHandler(onSuccess)
.getDataTable();
</script>
</head>
<body>
<div id="visualization_div" style="width: 600px; height: 380px;';"></div>
</body>
</html>
why is my data variable null in the onSuccesHandler and how do i get the datatable in the client
Thanks for your help
Its because you need to return a plain javascript array, not a data table which is purely a server-side object.
I am trying to get the URL for all the photos of a facebook page.
How do I get the 'source' URL for this query and JSON structure:
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=19292868552%3Ffields%3Dalbums.fields(photos.fields(source))&version=v2.1
I am using this success callback from a JSONP request:
function(response) {
for (i = 0; i < **???response.albums.data.length???**; i++) {
alert(**???response.albums.data[i].photos.data[i].source???**)
}
}
Can you help me find the right structure for the parts with the astericks? Because it has two [i]'s i think i'm getting confused..
You need to make sure that you have this in your head:
<script type='text/javascript' src='//connect.facebook.net/en_US/sdk.js'></script>
<script type='text/javascript' src='workFromPage.js'></script>
Now on workFromPage.js
var pre = onload;
onload = function(){
if(pre)pre();
if(!FB)reload();
var photoURLs = [];
// change userId
// make sure you test for login and wrap around code below, if needed
FB.api('/userId/albums', function(resp){
if(resp && !resp.error){
for(var i in resp){
FB.api('/'+resp[i].id+'/photos', function(r){
if(r && !r.error){
for(var n in r){
photoURLs.push(r[n].source);
}
// access photoURLs here
}
}
}
}
}
}
I'm using the following code to get google contacts name and phone number. Authorization page itself is not coming properly it shows error as "The page you requested is invalid". :( pls help me to solve this...
`
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("gdata", "1.x");
var contactsService;
function setupContactsService()
{
contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
}
function logMeIn() {
var scope = 'https://www.google.com/m8/feeds';
var token = google.accounts.user.login(scope);
}
function initFunc() {
setupContactsService();
logMeIn();
getMyContacts();
}
function checkLoggedIn(){
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.checkLogin(scope);
if(token != "")
return true;
else
return false;
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
//We load all results by default//
query.setMaxResults(10);
contactsService.getContactFeed(query, handleContactsFeed, ContactsServiceInitError);
}
//Gets the contacts feed passed as parameter//
var handleContactsFeed = function(result) {
//All contact entries//
entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var contactEntry = entries[i];
var telNumbers = contactEntry.getPhoneNumbers();
var title = contactEntry.getTitle().getText();
}
}
</script>
<body>
<input type="submit" value="Login to Google" id="glogin" onclick="initFunc();">
</body>`
Thanks
It looks like you are trying to use the Google Contacts 1.X API. That's been deprecated. Look at the JavaScript examples for the Google 3.X API and see if that helps.
You can try this example
var config = {
'client_id': 'Client ID',
'scope': 'https://www.google.com/m8/feeds'
};
inviteContacts = function() {
gapi.auth.authorize($scope.config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json", function(response) {
console.log(response);
//console.log(response.data.feed.entry);
});
}
Don't forget to add <script src="https://apis.google.com/js/client.js"></script> into your html file. Good Luck!