How to display viewCount YoutubeApi 3 - youtube-api

I've got this code, I've try to change a little bit with var v = value.statistics.viewCount; but nothing work for me, I've try to find a answer but without any result...
$(document).ready(function () {
$( $grid ).masonry( 'reloadItems' );
$( $grid ).masonry( 'layout' );
$('.add1').click(function (event) {
event.preventDefault();
var searchTerm = $('#query').val();
getRequest(searchTerm);
});
});
function getRequest(searchTerm) {
url = 'https://www.googleapis.com/youtube/v3/search';
var params = {
part: 'snippet',
key: 'AIzaSyA8OmKcw2DMNkJicyCJ0vqvf90xgeH52zE',
q: searchTerm,
maxResults:10
};
$.getJSON(url, params, function (searchTerm) {
showResults(searchTerm);
});
}
function showResults(results) {
var html = "";
var entries = results.items;
$.each(entries, function (index, value) {
var title = value.snippet.title;
var thumbnail = value.snippet.thumbnails.high.url;
var v = value.statistics.viewCount;
var description = value.snippet.description;
var videoID = value.id.videoId;
html += '<div class="item" title="' + title + '">' + '<img class= "vidth" id="' + videoID + '" src="' + thumbnail + '" ><div class="info"><p1>' + title+'</p1><hr><p2>'+description+'</p2><hr><p3>'+v+'</p3></div></div>';
});
$('.masonry').append(html);
$( $grid ).masonry( 'reloadItems' );
$( $grid ).masonry( 'layout' );
}
any ideas ?

You are trying to get viewCount from the statistics part, but you only queried for the snippet part.
You can only query for the statistics from the videos.list endpoint - it is not available through the search endpoint.
You will have to take the ids from the search results and then do a videos.list query for those ids to get the statistics on each and therefore the viewCount. See https://developers.google.com/youtube/v3/docs/videos/list

Related

how to use infowindow (google map API) to get back the ID of the selected location

I am displaying a list of locations (that i get through ViewBag for now) on a map and ask the user to choose one of them.
I have populated my infowindows with HTML code by looping through the list of locations.
now when the user clicks on one of the buttons in the infowindow ("Choose this one"), I want to update the view model (Venue) to include Venue.Id = the choosen location and submit back to the controller so update the database. how can I do such a thing ?
thanks a lot for your help.
here is my script code:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<section class="scripts">
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
function Initialize() {
google.maps.visualRefresh = true;
var rabat = new google.maps.LatLng(34.019657, -6.831833);
var mapOptions = {
zoom: 11,
center: rabat,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var list =
#Html.Raw(Json.Encode(((IEnumerable<KayenChiMVC.Models.Venue>)ViewBag.TheVenue).Select(v => new
{
venueId = v.VenueID,
venueName = v.Name,
venueDistrict = v.District,
venueType = v.SurfaceType,
venueLat = v.Latitude,
venueLon = v.Longitude
})
));
var infowindow = new google.maps.InfoWindow();
for(var i=0; i<list.length;i++){
var pos = new google.maps.LatLng(list[i].venueLat, list[i].venueLon);
var html = "<table>" +
"<tr><td>Nom:</td>" + "<td> " + list[i].venueName +" </td> </tr>" +
"<tr><td>Quartier:</td>" + "<td> " + list[i].venueDistrict +" </td> </tr>" +
"<tr><td>Type de surface:</td>" + "<td> " + list[i].venueType +" </td> </tr>" +
"<tr><td></td><td><input type='button' value='Choisir ce terrain' onclick=''/></td></tr>";
createMarker(pos, list[i].venueName, html);
function createMarker(pos,title, html){
var marker = new google.maps.Marker({
'position': pos,
'map': map,
'title': list[i].venueName
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
}
}
</script>
</section>
Add a data-id attribute to your input to hold the venue id.
<input id="myButton" type="button" data-id="123" value="Choose this one" />
and get the data-id attribute in javascript
document.getElementById('myButton').onclick = function() {
console.log(this.getAttribute('data-id')); // will log '123'
};

JQM Check Box Not Styling inside Webview ".trigger('create')"

Here is my javascript code snippet:
<script>
function returnStringForID(param) {
var retStr =
param.replace(/[\. ,:-]+/g, '').replace(/'/g, '')
.replace(/&/g, '').replace(/\(|\)/g, '');
return retStr;
}
$(document).ready(function () {
var chanId = 'Demo';
var fs_dyn = $('#fs_dyn');
var data = ['Sony', 'Pix', 'Max', 'Set'];
var seriesColors = ['#4000E3', '#FFC526', '#FF0000', '#C0504D'
, '#1F497D', '#4BACC6', '#8064A2', '#9BBB59', '#F79646', '#948A54'];
for (var i = 0; i < data.length; i++) {
var checkId = "graphItem_" + i;
var color;
color = seriesColors[i];
var chanId = returnStringForID(data[i]);
var tmp = "";
tmp = "<input type='checkbox' checked='true' class='custom' value='" + data[i]
+ "' id='" + chanId + "' name='" + chanId + "'/>"
+ "<label for='" + chanId + "' style='font-size:12pt;font-weight:bold;color:"
+ color + "'>" + data[i] + "</label>";
fs_dyn.append(tmp);
}
fs_dyn.trigger('create');
});
</script>
Here is the HTML:
<td width='30%' style="vertical-align: top;" id="tdDynamic">
<fieldset data-mini='true' id='fs_dyn'></fieldset>
</td>
This code works perfect if done in raw html. However when inside a webview, checkbox doesn't style.
Also I have used .trigger('create') to style a nested collapsible in the same app which is also inside a webview, but that works fine.
PS: I am using JQM 1.3.1 version, just in case this helps.
Use pageinit event which is equivalent to .ready() or any jQuery Mobile events.
Demo
$(document).on('pageinit', function () {
// code
});
Using .ready() in jQuery Mobile isn't recommended, please refer to this post.

add image to jQuery UI autocomplete remote source with cache

I am using jQuery autocomplete remote source with caching. As per demo by jQUery UI website javascript of remote source with caching is
<script>
$(function() {
var cache = {},
lastXhr;
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
});
});
</script>
Now I want to add some code to above javascript to display image in autocomplete list. There is an excellent example for displaying image in jQuery autocomplete such as:
http://jsfiddle.net/3zSMG/ but it does not include caching part.
I have been trying but NOT able to integrate this example into the existing remote with caching javascript. Any help would be very much appreciated. Many thanks.
FOLLOW-UP: As suggested by Andrew Whitaker, I have updated my script as follow:
<script>
$(function() {
var cache = {},
lastXhr;
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response(cache[term]);
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
var results;
if ( xhr === lastXhr ) {
results = $.map(data, function(item) {
return {
value: item.value,
avatar: item.avatar
};
});
cache[term] = results;
response(results);
}
});
},
}).data("autocomplete")._renderItem = function (ul, item) {
if ( item.value != null ) {
if ( item.avatar != null) {
return $("<li/>")
.data("item.autocomplete", item)
.append("<a><img src='images/" + item.avatar + "' />" + item.value + "</a>")
.appendTo(ul);
}
else {
return $("<li/>")
.data("item.autocomplete", item)
.append("<a>" + item.value + "</a>")
.appendTo(ul);
}
}
};
});
And content of search.php:
<?php
require_once "config.php";
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "select id, subject as value, avatar from Suggests where subject LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=(int)$row['id'];
$row['avatar']=$row['avatar'];
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
?>
I am able to see images in autocomplete list. But there is an issue: After keying in few letters, autocomplete list is shown up, if I continue adding some more random letters to expect autcomplete list to disappear (because the userinput no longer matches) but it does not. Andrew's example work well. Is there anything wrong with my javascript? Trying to debug by Firebug, I got error: TypeError element is null.
The key to the image portion of the demos is overriding the _renderItem function to change the li's that are generated to suggest items. This usually means that your source is an array with objects that have a label and/or value property, as well as a property that allows you to display the image correctly inside of _renderItem.
The caching code just stores the search term and results in a hash and looks in that hash before hitting the server.
Using the JSFiddle you linked as an example, here's something using StackOverflow's API that does caching and images:
$(document).ready(function() {
var cache = {},
lastXhr;
$("#auto").autocomplete({
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.ajax({
url: "http://api.stackoverflow.com/1.1/users",
data: {
filter: request.term,
pagesize: 10
},
jsonp: "jsonp",
dataType: "jsonp",
success: function(data, status, xhr) {
var results;
if (xhr === lastXhr) {
results = $.map(data.users, function(el, index) {
return {
value: el.display_name,
avatar: "http://www.gravatar.com/avatar/" + el.email_hash
};
});
cache[term] = results;
response(results);
}
}
});
},
delay: 500
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.value + "</a>")
.appendTo(ul);
};
});​
Notes:
This example is more complex than the examples on jQueryUI's website because the data from the API has to be transformed (to have avatar/value properties). The important thing to note is that we're caching the received values after the $.map call transforms the result array.
This looks complicated but just remember the two guidelines at the top of the answer and you should be good.
Example: http://jsfiddle.net/rK7TS/
Here's what I did:
lastXhr = $.getJSON( action, request, function( data, status, xhr ) {
if( data && data !== null ) {
var results;
if( xhr === lastXhr ) {
results = $.map(data, function(item) {
return {
value: item.value,
avatar: item.avatar
};
});
cache[term] = results;
response(results);
}
} else {
response([{ value: 'No results found.', avatar: null}]);
}
});

Using JSON to display the data

I am a new to JSON, I am trying to make the menu that can click and display the data.
All the objects are return from the Controller of my asp.net mvc project.
This is my code :
<script language="javascript" type="text/javascript">
function ViewProduct() {
var searchVal = $("#txtsearch").val();
$.getJSON(url, function (data) {
var mainMenu = $("#content ul#navmenu-v");
$.each(data, function (index, dataOption) {
var new_li = $("<li class='level1' id='select_list'><a href='javascript:void(0);' id='" + dataOption.ID + "' class ='selectedcategory'>" + dataOption.Name + "</a>");
mainMenu.append(new_li);
$('a#' + dataOption.ID).click(function () {
var urlGetProByDep = '<%: Url.Content("~/") %>' + "Products/GetProductsByDepList";
t = dataOption.ID;
var data = {};
if (searchVal != "") {
data.depID = t;
data.Q = searchVal;
} else {
data.depID = t;
}
$(".brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$(".brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
$(".brand_id").html( value.Name + "</br>" + value.PictureName + "</br>" + value.ID);
});
});
});
});
}
$(document).ready(function () {
ViewProduct();
});
The other block of menu code works very well , just have a problem with this block of my code above :
$.getJSON("ProductListing/Index", data, function (product) {
$(".brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
$(".brand_id").html( value.Name + "</br>" + value.PictureName + "</br>" + value.ID);
});
});
});
It is the block that I take the the object of JSON to display the in my view, but when I click on the menu , It shows only the element at the last of JSON object.
This is my JSON :
{"ja":
[
{"Name":"ABC1","PictureName1":"my image name1","ID":1},
{"Name":"ABC2","PictureName2":"my image name2","ID":2}
]}
Each menu is the department of each product. And if I do not loop the product data in the menu block, I cannot take the ID of the department to query to get the product in each department.
Any idea or question are welcome, Thanks you for taking your time.
You seem to have a copy&paste-error in your code, you will do 2 request to exactly the same url after each other - not even using the results of the first request. I guess you only wanted something like
$(".brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
$(".brand_id").html( value.Name + "</br>" + value.PictureName + "</br>" + value.ID);
});
});
But your problem is the .html() method. You are looping over your products, and in each turn you set the html of each .brand_id-element to a new value. So the result you see is what you have set to all elements in the last iteration. What you would need to do is set the HTML of each element on its own, each with a different content.
Yet, instead of emptying the list items and readding new contents to them (maybe the number of your products changes each query request), I'd rather remove all items and append new ones:
$(".brand_id").remove();
$.getJSON("ProductListing/Index", data, function (product) {
var $parent = $("#parent"); // the parent node of the product list
$.each(product.ja, function (index, value) {
$parent.append('<li class="brand_id">' + value.Name + '<br />' + value.PictureName + '<br />' + value.ID + '</li>');
});
});
(edit) ...or, if brand_id really is an id:
var $parent = $("#brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
$parent.append('<div>' + value.Name + '<br />' + value.PictureName + '<br />' + value.ID + '</div>');
});
});
You are subscribing to the .click event of the anchor inside a $.each call. But since you have captured the dataOption variable you are using to prepare the AJAX request in a closure, it is obvious that by the time you click on the link, this dataOption variable is already pointing to the last element of the array you are looping over. So you could pass the argument to the click callback like this:
<script type="text/javascript">
function ViewProduct() {
// TODO: There's some url variable used here which is nowhere defined => define it
$.getJSON(url, function (data) {
var mainMenu = $("#content ul#navmenu-v");
$.each(data, function (index, dataOption) {
$(mainMenu)​.append(
$('<li/>', {
'class': 'level1',
// TODO: find an unique id or you get broken HTML
'id': 'select_list',
'html': $('<a/>', {
'href': '#',
'id': dataOption.ID,
'class': 'selectedcategory',
'text': dataOption.Name,
'click': function(arg) {
return menuClick(arg);
}({ dataOption: dataOption })
})
})
);​
});
});
}
function menuClick(arg) {
var urlGetProByDep = '<%= Url.Action("GetProductsByDepList", "Products") %>';
var t = arg.dataOption.ID;
var data = { };
var searchVal = $('#txtsearch').val();
if (searchVal != '') {
data.depID = t;
data.Q = searchVal;
} else {
data.depID = t;
}
$('.brand_id').empty();
var url = '<%= Url.Action("Index", "ProductListing") %>';
// TODO: Are those 2 nested AJAX calls really necessary here?
$.getJSON(url, data, function (product) {
$('.brand_id').empty();
$.getJSON(url, data, function (product) {
$.each(product.ja, function (index, value) {
$('.brand_id').html( value.Name + "</br>" + value.PictureName + "</br>" + value.ID);
});
});
});
}
$(document).ready(ViewProduct);
</script>
Also notice that I have moved the searchVal declaration inside the click callback in order to account for changes of its value between the time the page is loaded and the user actually clicking on the link.

$.ajax({url:link}) and Jquery UI Droppable

I have a problem.
I drop element into #projectsActive. New element have been created there. Old element have been deleted with fadeOut
But ajax query sometimes isn't running.
What's the reason?
$("#projectsActive").droppable({
drop: function (event, elem)
{
var e = elem.draggable;
var linkToSend = "/Projects/Publish/" + $(e).attr("projectid");
$.ajax({ url: linkToSend });
var projectid = $(e).attr("projectid");
var innerText = "";
if ($(e).find("a").length > 0)
{
innerText = $(e).children("a").html();
}
else
{
innerText = $(e).html();
}
var newObject = '<li class="project dragg" projectid="' + projectid + '">' + innerText + '</li>';
$(e).fadeOut("fast", function ()
{
$("#projectsActive").append(newObject);
$(this).remove();
BindDrags();
});
}
});

Resources