Youtube-like like/dislike rating system code wanted? - youtube

I am trying to make a rating system, very similar to Youtube's thumbs Up/Down.
Actually, I was hoping to achieve exactly the same.
But from what I gather from here: http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html#Ratings
Youtube uses an API to take care of all the Ratings.
So I am looking for info and help on how can I set up the same system YT has.
I basically want to have a Like/Dislike function for every page, which is liked to a specific object on that page - just like the like/dislike is linked to a video on every page. Preferrably also one for comments.
All help is very very welcomed. From source-codes for already done systems (I searched around google quite a bit, but never found a similar open-source rating system) to help and info on how I can set up the API-powered rating system.

For the database part, if you need to know which users liked which videos, then use
two tables, one for likes and one for dislikes:
TABLE likes {
user_id
video_id
}
TABLE dislikes {
user_id
video_id
}
Both tables associate a user with a video.

I would suggest having a database with all videos and comments, that has a field for likes and dislikes. you can then update the database with javascript click events to perform ajax calls to increment the count. you could use jquery and the code would be as simple as:
$('#up_button').click(function(){
var id = $(this).attr('thisid');
$.ajax({ type: 'POST',
url: 'AJAX/Handler/Upvote',
data: { video_id: id },
dataType: 'html',
success: function (data) { alert('success'); },
error: function (xhr, err) { alert('Error:\n\nreadyState: " + xhr.readyState + "\nstatus: " + xhr.status + "\nresponseText: " + xhr.responseText); }
});
});

Related

Rails Frontend Trying to save autogenerated data to database without form

I'm new to ruby on rails. I'm trying to save data that is generated by itself to the database. i have looked into and found I was meant to use ajax, however all the videos/forums i have seen are example of ajax that use form and not refreshing page. i want to save data automatically without pressing submit.
Assume that the project is fresh project with postgresql as the database. I have created a database that can hold geo points by using postgis. i have created another page where it has map implemented where i can manully pin location. I want to save the manuuly pinned location to the database.
function onMapClick(e) {
alert("You clicked the map at " + e.latlng);
}
mymap.on('click', onMapClick);
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);
The e.latlng holds the geopoint, but i dont know how to save it the database if the user clicks anywhere on the map.
You don't need submit form to use ajax.
Basically what you want is add event listener to the map, and when user click then send ajax request to the controller.
For example, let's say that your map is inside div with id my-map.
If you use jQuery you can write something like this:
$('#my-map').on('click', function() {
# add your logic here
$.ajax({
url: 'your-url',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
'let': data you want to send to backend
})
}
Hope it works!
EDIT:
After I looked your code I found that you can not have jQuery in your project so you can not use jQuery ajax. You need use vanilla javascript. So instead this snippet above, you can write this.
var xhttp = new XMLHttpRequest();
const params = { saving_location: { geoPoints: e.latlng } }
xhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
alert(http.responseText);
}
}
xhttp.open("POST", "/saving_locations", true);
xhttp.setRequestHeader('Content-Type', 'application/json', 'Accept', 'application/json');
xhttp.send(JSON.stringify(params));
Also add protect_from_forgery with: :null_session in your application controller and skip_before_action :verify_authenticity_token in your Saving Location controller.(under before_action).
Here is good blog post why you need this https://blog.nvisium.com/understanding-protectfromforgery
Please notice that you wan't save your database, because your geoPoints type in database is type of point and you send string to rails controller. I never work with points in rails so I can not help you here.(You can always add two columns in db, one for longitude and one for latitude and then store numbers instead point)

Instagram API request single username

I'm using this way to get the username data from Instagram:
https://api.instagram.com/v1/users/search?q=[USERNAME]&client_id=[CLIENT ID]
It works fine, but has a flaw - the username search actually gets ALL usernames starting with the string you set.
Why/How is that happening ?
There is a limit of 52 username results, so is there a way to increase it, because if you search "asdasd" (which is an existing account!) you would get probably a million accounts ?
Is there a work-around, because I want to search for the exact username ?
So it seems there is only this API for this functionality. You can simply use this workaround: make your request as you are doing it right now, then you can filter out the single item you need. You can iterate through the list of users, and only keep the one, where the username is exactly the same as you have specified.
SOLUTION:
Put the username in quotations like this (username: asdasdasd):
https://api.instagram.com/v1/users/search?q="asdasdasd"&client_id=[CLIENT ID]
Which results in (the results that interests you is highlighted):
- if you don't use the quotations there's a big chance that the desired username won't appear in the results!
If there are more than one results use this code the iterate through the response data to find your one and get it's ID, full_name etc.
function getUserID() {
//send request for the user info on click
$('.btn-user-request').click(function(){
var searchTerm = $('.input-user-request').val();
if(searchTerm == ''){
$('.user-id-value').html('Enter a username!');
}
else{
$.ajax({
url: "https://api.instagram.com/v1/users/search?q=\"" + searchTerm + "\"&client_id=5fc90c90b885487485125d6df440fefd",
dataType: 'jsonp'
}).done(function(data) {
if(data.data[0] == []){
$('.user-id-value').html('No username found!');
}
else{
for(i=0;i<data.data.length;i++){
var userInformation = data.data[i];
if(userInformation.username == searchTerm){
$('.user-id-value').html(userInformation.id);
break;
}
}
}
});
}
});
//simulate the button click, on click of the Enter key
$(".input-user-request").on('keydown', function(){
if(event.keyCode == 13){
$(".btn-user-request").click();
}
});
}
See JSFiddle
(for some reason the code doesn't format properly)
I would suggest to try username "jack".
In fact none of suggested methods work for this.
I tried with max_id, min_id, it does not work either.
So it is exact flaw in API, and there is no such documentation on Instagram API to help to solve this.
So finding exact user id by it's username is quite a problem for popular names.
The only one solution for today I found is parsing user's Instagram HTML page and get it's id from there. This is very stupid, but this is only one solution which works in all cases right now :(
It's simple:
https://www.instagram.com/{username}/?__a=1

bing maps autocomplete get long and lat from address

I want the user to search for an address and i want it to show som examples and when the user chooses one the examples i want it to find the coordinates. But for now i can't get autocomplete to work at all and it won't search for addresses.
$('[id$=PlaceOfDeparture]:not(.ui-autocomplete-input)').live('focus', function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: "http://dev.virtualearth.net/REST/v1/Locations",
dataType: "jsonp",
data: {
key: 'AvmdDLtsmPpOQ9N21vLDEAlhnr-H-W-A9HmjXiIDn9cHBVp5ylLELdc_lmnuCcRB',
addressLine: request.term,
},
success: function (data) {
var result = data;
}
});
},
minLength: 2,
select: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
travel = $(this).closest('div').parent();
travel.find('[id$=PlaceOfDepartureCoordinates]').val(ui.item.value);
travel.find('[id$=PlaceOfDepartureContry]').val(ui.item.countryName);
$(this).change();
updateMap();
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
You can find a working code sample of how to do this here: http://www.vivienchevallier.com/Articles/use-bing-maps-rest-services-with-jquery-to-build-an-autocomplete-box-and-find-a-location-dynamically
However, I highly recommend against doing this. Autocomplete usually generates a high volume of transactions against your account. If you are using an enterprise account this will result in high costs. If you are using a non-enterprise account you will run into issues where the auto complete will not work all the time as your account with be rate limited due to the high frequency of requests.
A much better approach to create the type of functionality you are looking for is to create a user ranked auto suggest. This will drastically improve the suggestions to the user and will make for a much better user experience while minimizing the amount of wasteful calls made to the Bing Maps service. The idea behind the user ranked auto suggest is to create a database where you can store the locations selected by your users. Every time a user selects a location in the auto suggest a rank value is increased and the ordering of the suggestions is based on the rank value. If the user does not find any results in the auto suggest that match their query, that's when they press the search button and you call the Bing Maps service to return possible results. If they select any of the results you would then add that result to your database. I have a couple of customers who have done this and after a few months they were hardly generating any transactions against Bing Maps which meant lower costs over the long term. It also meant that they had a lot of insight into what their users are looking for and which locations were the most popular. This kind of insight can be very valuable.
This is an very old post. Bing Maps now offers autosuggest. Here are some resources:
http://bingmapsv8samples.azurewebsites.net/#Fill%20Address%20Form%20with%20Autosuggest
http://bingmapsv8samples.azurewebsites.net/#Custom%20Autosuggest%20Input%20with%20JQuery%20UI
https://msdn.microsoft.com/en-us/library/mt750287.aspx
You may also want to consider Azure Maps which provides autosuggest for addresses, POI, and POI categories:
https://azure.com/maps
https://learn.microsoft.com/en-us/rest/api/maps/search/getsearchaddress
Simply use the typeahead URL parameter.

Counting clicks to external links with rails

I have Entry model with url field, which contains link to external site.
In view I list these links, and now I'd like to start counting when someone clicks it, and keep this info in database. What's the best way of doing it?
You can easily use google analytics to track outbound links: http://support.google.com/analytics/bin/answer.py?hl=en&answer=1136920
If that is not an option you will need to add some javascript to your links make an ajax request to the server to increment the count before transferring the user to the new url. Something similar to this jquery code:
$('a').click(function(){
var stored_ulr = $(this).attr('href');
$.ajax({
url: #your server url to increment count,
data: #data you need to send,
success: function() { window.location = stored_url; },
});
return false;
});
The above code is just a general outline. You will have to fill in the blanks and make it work for your needs.

Twitter Tweet or ReTweet Callbacks

Hope you are having a good time.
I am creating a website where when users Tweet a wordpress blog entry then they get points on the websites.
So basically, if a user Tweets that entry on his Twitter then we would give him some points to use on the website (not money). Although this thing is plausible with Facebook but not with Twitter in my knowledge.
I am willing to try to both ways by Twitter Tweet Button or TweetMeme Retweet Facility. However, I could not find a facility for a callback at neither of these.
I am implementing a similar functionality in Facebook and I can see the light at the end of the tunnel with using FBML JS SDK. HOwever, if something similar can be achieved with Twitter then it would be awesome.
Would love to hear more from you guys,
Kind Regards,
Khuram
They've fixed this with the intents function:
https://dev.twitter.com/pages/intents-events
twttr.events.bind('tweet', function(event) {
// Do something there
});
or for clicking
twttr.events.bind('click', function(event) {
var click_type = event.region;
});
using Twitters #anywhere api, you can set an onTweet function that does something when someone tweets.
here is a 6-step tutorial, see number 4
A default tweetBox can be called after the element with the comments class with the following snippet.
twttr.anywhere(function(twitter) {
twitter(".comments").tweetBox();
});
So if you want a custom label, content, and a callback when the tweet has been sent, use this code.
twitter(".comments").tweetBox({
label: 'What do you think about this article?',
defaultContent: '#nettuts ',
onTweet: function(plain, html){
// Actions when tweet is sent
}
});
opening tweet intent pop from JS code will send a callback. You need to put your tweet URL in herf of anchor tag
HTML:
<a target="_blank" href="https://twitter.com/intent/tweet?text=itismytext&url=http://google.com"> twitter share</a>
JavaScript:
$(document).ready(function(){
twttr.events.bind('tweet', function(event) {
console.log(event);
// OR
alert(JSON.stringify(event));
});
});

Resources