Displaying Twitter stream on webpage? - twitter

I want to display a twitter feed of a user on my website. What is the simplest way to do this? I guess Javascript. What I want specifically is for the last 5 tweets to load & then, when another tweet is made, for that to automatically appear at the top of the Tweets. It needs to cover pretty much the whole website, apart from the header & footer. Any suggestions/code to do that?
Cheers, help greatly appreciated!

Loading new data without refreshing will need to be AJAX. To get the data, ses the Twitter API http://apiwiki.twitter.com/. The API will allow you to get the data in the format of choice (xml, json, ect...) which you can then parse and return either the data or HTML to the page that submitted the AJAX call. That should give you a push in the right direction.

Simplest way would be adding the Twitter widget : http://twitter.com/goodies/widget_profile and it updates new tweets automatically (using AJAX I think). You ca set the dimensions too.

use any twitter wrapper calss for example this http://emmense.com/php-twitter/ to get the status and display it. than use javascript time function inside function make ajax call to php script and append latest tweet on top of your container.
you can use jquery for dom update
$('#dividhere').prepend('Bla bla bla');

use jQuery, sry for my programming language, but i like our czech lang
<script type="text/javascript">
jQuery(document).ready(function($){
$.getJSON('http://api.twitter.com/1/statuses/user_timeline/##USERNAME##.json?count=2&callback=?', function(zpravicky){
$("#twitter").html(formatujExtSocialniProfil(zpravicky));
});
});
</script>
in external javascript file code like this
function formatujExtSocialniProfil(twitters) {
var statusHTML = [];
for (var i=0; i<twitters.length; i++){
var username = twitters[i].user.screen_name;
var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
return ''+url+'';
}).replace(/\B#([_a-z0-9]+)/ig, function(reply) {
return reply.charAt(0)+''+reply.substring(1)+'';
});
statusHTML.push('<li><span>'+status+'</span> <br/><b>'+relative_time(twitters[i].created_at)+'</b></li>');
}
return statusHTML.join('');
}
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
if (delta < 60) {
return 'seconds ago';
} else if(delta < 120) {
return 'minute ago';
} else if(delta < (60*60)) {
return (parseInt(delta / 60)).toString() + ' minutes';
} else if(delta < (120*60)) {
return 'hours ago';
} else if(delta < (24*60*60)) {
return 'ago ' + (parseInt(delta / 3600)).toString() + ' hours';
} else if(delta < (48*60*60)) {
return 'yesterday';
} else {
return 'since ago' + (parseInt(delta / 86400)).toString() + ' days';
}
}

Related

Dropzone.js and form validation

Is it possible not to break the nice Rails form validation errors displayed after marking the whole form the 'dropzone' class?
Now, when I try to submit the form, nothing changes and the page stays at it was without providing any info for user which fields doesn't meet the requirements. Controller renders JSON response (dropzone using consequence) which seems to not be processed by the view.
Thank you in advance for your quick response.
My workaround for this problem:
Dropzone.options.filedrop = {
init: function () {
// Other triggers not listed
// ...
this.on("error", function (file, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
// Build an unordered list from the list of errors
var _ref, _results, _i, _len;
if ($.isPlainObject(response)) { // Check if response is in JSON format for showing standard form errors
// Remove errors from accepted image
file.previewElement.classList.remove("dz-error");
_ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_results.push(node.textContent = null);
}
file['status'] = 'success';
console.log("acceptedImage: " + JSON.stringify(file));
var json = response;
var errorText = "<div id=\"error_explanation\"><h2>" + Object.keys(json).length + " errors prohibited this thing from being saved:</h2><ul>";
$.each(json, function (key, value) {
errorText += "<li>" + key.capitalize() + ' ' + value[0] + "</li> ";
});
errorText += "</ul></div>";
console.log("errorText: " + errorText);
// Insert error list into form
$('.errors_placeholder').html(errorText);
} else {
if (myDropzone.files.length > 1) {
myDropzone.removeFile(myDropzone.files[0]);
}
}
});
}
};
You need to parse the JSON response into your js callback yourself, something like this:
Dropzone.options.filedrop = {
init: function () {
this.on("complete", function (file, jsonResponse) {
console.log(jsonResponse);
//do stuff with the jsonResponse here
});
}
};

Why my md-autoComplete is not displaying return values

I am using Angular Material for the first time. I am stuck with an issue with autocomplete. Below is my template:
<md-autocomplete class="flex"
md-no-cache="true"
md-selected-item="c.receipt"
md-item-text="item.name"
md-search-text="SearchText"
md-items="item in querySearch(SearchText)"
md-floating-label="search">
<md-item-template>
<span><span class="search-result-type">{{item.GEOType}}</span><span md-highlight-text="SearchText">{{item.GEOName+(item.country?' / '+item.country:'')}}</span></span>
</md-item-template>
<md-not-found>No matches found.</md-not-found>
</md-autocomplete>
And in ctrl I have:
$scope.querySearch = function (query) {
var GeoDataAPIUrl = '/api/TargetSettings/RetrieveCorridorLeverValues';
if (query.length < 5)
return;
else {
var GeoDataSearchUrl = GeoDataAPIUrl + '?' + 'strGeoName=' + query;
$http
.get(GeoDataSearchUrl)
.then(function (geoAPIResponse) {
console.log("GeoAPIResponse was ", geoAPIResponse);
return geoAPIResponse.data;
},
function (geoAPIError) {
console.log("GeoAPI call failed ", geoAPIError);
});
}
};
With above code, I am getting nothing as suggestions, only my not-found text is displayed, while my http call return an array which is printed in console too. Am I missing something??
I saw at many places, people have used some filters with autocomplete, I dont think that is something essential.
Pls advice how to make above work.
$http returns promise and md-autocomplete uses same promise to display the result. In your case you are returning result but not promise. Your code should be
$scope.querySearch = function (query) {
var GeoDataAPIUrl = '/api/TargetSettings/RetrieveCorridorLeverValues';
if (query.length < 5)
return;
else {
var GeoDataSearchUrl = GeoDataAPIUrl + '?' + 'strGeoName=' + query;
var promise = $http.get(GeoDataSearchUrl).then(function (geoAPIResponse) {
console.log("GeoAPIResponse was ", geoAPIResponse);
return geoAPIResponse.data;
},
function (geoAPIError) {
console.log("GeoAPI call failed ", geoAPIError);
});
return promise;
}
};
It will work now.

youtube data api retrieve view counts

i implemented in my .net project api youtube.
this is my code
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "MY_API_KEY",
ApplicationName = "MY_APPLICATION_NAME"
});
var searchListRequest = youtubeService.Search.List("snippet");
searchListRequest.Q = SearchText;
searchListRequest.MaxResults = 50;
searchListRequest.Order = SearchResource.ListRequest.OrderEnum.ViewCount;
var searchListResponse = await searchListRequest.ExecuteAsync();
foreach (var searchResult in searchListResponse.Items)
{
if (searchResult.Id.Kind == "youtube#video")
{
}
}
in searchResult not have a STATISTICS (for example view counts).
How to?
Because search.list don't have the part statitics you need to call two time the API.
One time with the request search.list
You get the id of the channel
And a second call with channel.list, with the id of the channel and parameter: statistics
Then you have viewCount
Doc can help : https://developers.google.com/youtube/v3/docs/search/list
https://developers.google.com/youtube/v3/docs/channels/list
I came across the same problem using their Javascript based API search functionality.
Looks like they do not have a build in "views" option for their search based API.
https://developers.google.com/youtube/v3/docs/search#snippet
How ever, you can use their JSON based API and create a AJAX based search box, which returns a JSON based response with a option for view count!
https://developers.google.com/youtube/2.0/developers_guide_jsonc
Created this myself, check it out:
$(document).ready(function() {
var q = $('#query');
$('#search-button').click(function(e) {
var url = "https://gdata.youtube.com/feeds/api/videos?q=" + q.val() + "&v=2&alt=jsonc";
$.getJSON( url, function( response ) {
for(var i = 0; i < response.data.items.length; i++) {
var tr = "<tr>",
title = "<td>" + response.data.items[i].title + "</td>",
views = "<td>" + response.data.items[i].viewCount + "</td>",
likes = "<td>" + response.data.items[i].likeCount + "</td>",
dislikes = "<td>" + (response.data.items[i].ratingCount - response.data.items[i].likeCount) + "</td>",
endtr = "</tr>";
$('#search-container').append(tr + title + views + likes + dislikes + endtr);
}
});
e.preventDefault();
});
});
http://jsfiddle.net/19m9tLo3/1/

Google Calendar not displaying correct time

I have a Google Calendar for a school website I'm working on and am using the Google API to display the next five calendar events. One problem is that the time displays on a 24 hour clock instead of AM and PM, but that's not my main problem. The main problem is that while the events display the correct time on the website, when you click on the event to view it in the calendar event view, it will only display GMT time instead of Eastern Time. While logged into the Google account, the events display the right time zone, but whenever you view it while not logged in, it defaults to GMT.
I have tried changing it to another time zone and change it back, didn't fix it.
I also made sure all settings in both the calendar and the account were set to Eastern time zone, at least everywhere I could find it.
I've seen a lot of people with similar problems on Google sites using the ical or other feeds, but I haven't seen anyone with the problem using a code similar to mine.
The website is live: http://fletcheracademy.com. And here is the main javascript code that pulls it.
There's probably some details I'm missing, let me know if there's anything else you need to know. Thanks so much!
<script type="text/javascript">
google.load("gdata", "2.x");
function init() {
google.gdata.client.init(handleGDError);
loadDeveloperCalendar();
}
function loadDeveloperCalendar() {
loadCalendarByAddress('fletcheracademycalendar#gmail.com');
}
function padNumber(num) {
if (num <= 9) {
return "0" + num;
}
return num;
}
function loadCalendarByAddress(calendarAddress) {
var calendarUrl = 'https://www.google.com/calendar/feeds/' +
calendarAddress + '/public/full';
loadCalendar(calendarUrl);
}
function loadCalendar(calendarUrl) {
var service = new
google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
query.setOrderBy('starttime');
query.setSortOrder('ascending');
query.setFutureEvents(true);
query.setSingleEvents(true);
query.setMaxResults(5);
service.getEventsFeed(query, listEvents, handleGDError);
}
function handleGDError(e) {
document.getElementById('jsSourceFinal').setAttribute('style', 'display:none');
if (e instanceof Error) {
alert('Error at line ' + e.lineNumber + ' in ' + e.fileName + '\n' + 'Message: ' + e.message);
if (e.cause) {
var status = e.cause.status;
var statusText = e.cause.statusText;
alert('Root cause: HTTP error ' + status + ' with status text of: ' + statusText);
}
} else {
alert(e.toString());
}
}
function listEvents(feedRoot) {
var entries = feedRoot.feed.getEntries();
var eventDiv = document.getElementById('events');
if (eventDiv.childNodes.length > 0) {
eventDiv.removeChild(eventDiv.childNodes[0]);
}
var ul = document.createElement('ul');
//document.getElementById('calendarTitle').innerHTML =
// "Calendar: " + feedRoot.feed.title.$t;
var len = entries.length;
for (var i = 0; i < len; i++) {
var entry = entries[i];
var title = entry.getTitle().getText();
var startDateTime = null;
var startJSDate = null;
var times = entry.getTimes();
if (times.length > 0) {
startDateTime = times[0].getStartTime();
startJSDate = startDateTime.getDate();
}
var entryLinkHref = null;
if (entry.getHtmlLink() != null) {
entryLinkHref = entry.getHtmlLink().getHref();
}
var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
if (!startDateTime.isDateOnly()) {
dateString += " " + startJSDate.getHours() + ":" +
padNumber(startJSDate.getMinutes());
}
var li = document.createElement('li');
if (entryLinkHref != null) {
entryLink = document.createElement('a');
entryLink.setAttribute('href', entryLinkHref);
entryLink.appendChild(document.createTextNode(title));
li.appendChild(entryLink);
li.appendChild(document.createTextNode(' - ' + dateString));
} else {
li.appendChild(document.createTextNode(title + ' - ' + dateString));
}
ul.appendChild(li);
}
eventDiv.appendChild(ul);
}
google.setOnLoadCallback(init);
</script>
Try this!
Where you have:
var calendarUrl = 'https://www.google.com/calendar/feeds/' + calendarAddress + '/public/full';
you should add something like:
&ctz=Europe/Lisbon
Check here for the correct name of your timezone.

Adding 'Data-Filter' True in code to UL, but doesnt show up on page

So I want to add the data filter to the UL if there are certain number of LI's. I get the attr to add correctly, but nothing shows up on page.
else
{
$('#presentations').attr("data-filter", "true");
$('#presentations').html('');
for (var i = 0; i < results.rows.length; i++) {
$('#presentations').append(
'<li>' + results.rows.item(i).presentName + ''
+ 'delete</li>');
}
}
$('#presentations').listview('refresh');
$.mobile.changePage($('#dashboard'), {reloadPage: "true"} );
$('#dashboard .message').text('Your presentations');
}
I'm guessing its a caching issue but I can't figure out how to work around it. Help?
I've tried to re-initialize, recreate or refresh the listview but none of it works.
The only way I can get it working is by doing:
$('#listview').listview('option', 'filter', true);
$('#listview').trigger("listviewcreate");
So you trigger manual the listviewcreate event and before that you set the filter to true. (setting with attr(), data() or jqmData() also doesn't work)
Example:
http://jsfiddle.net/N7Z9e/143/
Here is the code in action - thanks Gerjan!
else {
// don't create duplicate/double filter
$(".ui-listview-filter").remove();
if (results.rows.length > 3) { //Add filter search if more than 3 presentations.
$('#presentations').listview('option', 'filter', true);
}
$('#presentations').html('');
for (var i = 0; i < results.rows.length; i++) {
$('#presentations').append(
'<li>' + results.rows.item(i).presentName + ''
+ 'delete</li>'
);
}
$('#presentations').listview('refresh');
$('#presentations').trigger("listviewcreate");
$.mobile.changePage($('#dashboard'), { reloadPage: "true" });
$('#dashboard .message').text('Your presentations');
}

Resources