Youtube tracking JQuery plugin jQuery.tubeplayer.js - javascript

thanks for having a look at my question,
I am trying to set up custom events (Analytics tracking) using the jQuery.tubeplayer.js plugin at http://www.tikku.com/jquery-youtube-tubeplayer-plugin#tubeplayer_tutorial_3
I can get the plugin working and attach events to onPlayerPlaying, onPlayerPaused,onPlayerEnded etc but cannot extract the data I want to pass to the event. I want to extract the URL of the video and the time of the video when the event is triggered. This data can be extracted from the video using the showData(jQuery('#youtube-player-container').tubeplayer('data')); function in the example, I cant seem to get this data into my event.
My code is as follows:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type='text/javascript' src='js/jQuery.tubeplayer.js'></script>
</head>
<body>
<div id='youtube-player-container'> </div>
<a onClick="showData(jQuery('#youtube-player-container').tubeplayer('data'));" href="javascript:void(0);">Click here to see data</a>
<div class="EventListener">The is the initial event listener text</div>
<a onClick="showVideoURL(jQuery('#youtube-player-container').tubeplayer('data'));">Click to see the URL of the video</a><br/>
<span class="VideoURL"></span><br/>
<div class="Bufferstatus">The is Buffertext</div>
<a onClick="showTime(jQuery('#youtube-player-container').tubeplayer('data'));">Click to see the time of the video</a><br/>
<span class="currentTime"></span><br/>
<script>VideoID="i3AqF9e8WV4"</script>
<script src="js/jQuery.tubeplayer.settings.js"></script>
with the script tubeplayer settings at
var url=location.href;
jQuery.tubeplayer.defaults.afterReady = function(){
//jQuery("#player").tubeplayer("cue", " ");
};
initPlayer();
function showData(data){
var html = "bytesLoaded : " + data.bytesLoaded;
html += " / bytesTotal : " + data.bytesTotal + "\n";
html += "currentTime : " + data.currentTime;
html += " / duration : " + data.duration + "\n";
html += "startBytes : " + data.startBytes + "\n";
html += "state : " + data.state + "\n";
html += "quality : " + data.availableQualityLevels.join(",") + "\n";
html += "url : " + data.videoURL + "\n";
html += "videoID : " + data.videoID;
alert(html);
}
function showTime(data){
$('.currentTime').text('The time when clicked was:' + data.currentTime);
}
function showVideoURL(data){
$('.VideoURL').text('The video URL is:' + data.videoURL);
}
showData(jQuery('#youtube-player-container').tubeplayer('data'));
function initPlayer(){
jQuery("#youtube-player-container").tubeplayer({
initialVideo: VideoID,
width: 600,
height: 450,
onPlayerPlaying: function(){$('.EventListener').text('The video is played at' + data.currentTime);},
onPlayerPaused: function(){$('.EventListener').text('The video is paused at' + data.currentTime);},
onPlayerEnded: function(){$('.EventListener').text('The video ended');},
onPlayerBuffering: function(){$('.Bufferstatus').text('The video is buffering');},
modestbranding: false,
showControls: 1,
onQualityChange: function(quality){$('.qualityCheck').text('The quality of the video is: ' +quality);}
});
};
The specific data is would like is the video URL, the time at which the event took place if possible. The data shows in the pop up when the tags are clicked.
Any help is greatly appreciated.
Thanks,
Simon

You should invoke $("#youtube-player-container").tubeplayer("data") every time you want to get information from the player. This is to ensure that you get the most up to date information.
The code inside of the onPlayerX events doesn't make any sense:
$('.EventListener').text('The video is played at' + data.currentTime);
since the 'data' object doesn't refer to anything.
Instead of using 'data.currentTime', use:
$("#youtube-player-container").tubeplayer("data").currentTime
and that should take care of your issue.
Alternatively, since you have setup the 'showTime' and 'showVideoURL' functions that take a data object, you can pass the .tubeplayer("data") object into those methods, like:
showTime( $("#youtube-player-container").tubeplayer("data") )
similarly to how showData is being used before initPlayer is defined.
Does that help?

Related

sending data from a search bar to a url

I am having trouble. So I need to get data from an api. I have a search bar and the user needs to input the search bar to look up a super hero api.
How would I get data from a search bar and put in my url all in a .click function.
var userInput;
var url;
var test;
//https://superheroapi.com/api/10215865526738981
$(document).ready(function () {
// when the user types in the data and clicks the button
$(btn1).click(function () {
// this is where the search bar is
userInput = document.getElementById('mySearch').innerHTML;
});
url = 'https://www.superheroapi.com/api.php/10215865526738981/search/batman' + userInput;
// here is where the api link in say type in batman
// and is should pop up with info about batman and
$.getJSON(url, function (data) {
var html = '';
$.each(data.results, function (i, demo) {
html += '<h2>' + demo.name + '</h2>';
//html += "<h2>" + demo.biography.alter-egos + "</h2>";
html += '<h2> Power Stats ' + demo.powerstats.combat + '</h2>';
html += '<p> Connections ' + demo.connections.relatives + '</p>';
html += '<p> appearance ' + demo.appearance.gender + '</p>';
html += '<h2> Work ' + demo.work.base + '</h2>';
html += ' Profile <img src ' + demo.image.url + '>';
});
$('#demo').html(html);
});
}
<p>
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<p id="demo"></p>
</p>
Here is something that works that you can use to compare with your code and make something out of it. I've used plain javascript and left comments what is going on so that you can learn from it.
There were few wrong assumptions in original question.
code was executing on page load and didn't wait for user input
url was hardcoded to start with batman + what ever user wrote
Code below is not perfect, but it is close enough to original code and it should be easy to understand. I also opted not to use jQuery, but you should be able to use it if wanted. Just replace getElementById with jQuery selectors and replace XMLHttpRequest with getJson.
I hope this helps you move ahead with your problem and that you will be able to learn something new which could help you better understand javascript. Happy coding!
var button = document.getElementById('btn1');
// when user clicks on button, we want to call function start search
button.addEventListener('click', startSearch);
function startSearch(event) {
// when we are starting the search, we want to pick up the value
// input field from user
var userInputValue = document.getElementById('mySearch').value;
// this is base API url on which we can add what user wanted
var urlBase = 'https://www.superheroapi.com/api.php/10215865526738981/search/'
// if user did not provide name in input, we want to stop executing
if (userInputValue === null || userInputValue === '') return;
// if we are still in this function, append what user typed onto urlBase
var searchUrl = urlBase + userInputValue;
// call function which actually executes the remote call
performSearch(searchUrl);
}
function performSearch(searchUrl) {
// this could be jQuery getJSON if you so prefer
// here it is vanila JS solution of how to get data via AJAX call
var requestData = new XMLHttpRequest();
// because AJAX is always async, we need to wait until file is loaded
// once it is loaded we want to call function handleResults
requestData.addEventListener('load', handleResults);
requestData.open('GET', searchUrl);
requestData.send();
}
function handleResults() {
// once we get response, because we used vanilla JS, we got response
// available in this context as "this.response", however it is type string
// we need to take that string and parse it into JSON
var responseJSON = JSON.parse(this.response);
// if there is error, we didn't find any character
if (responseJSON.error) console.log('Character not found');
else {
var html = '';
responseJSON.results.forEach(function (result) {
html += '<h2>' + result.name + '</h2>';
// html += "<h2>" + demo.biography.alter-egos + "</h2>";
html += '<h2>Power Stats ' + result.powerstats.combat + '</h2>';
html += '<p>Connections ' + result.connections.relatives + '</p>';
html += '<p>Appearance ' + result.appearance.gender + '</p>';
html += '<p>Work ' + result.work.base + '</p>';
// html += ' Profile <img src ' + result.image.url + '>';
})
// this is bad thing to do, injecting html like that into DOM
// but let's leave this lesson for later stage
// so, let's take this html and drop it onto the page
document.getElementById('demo').innerHTML = html;
}
}
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<div id="demo"></div>
const value = document.getElementById('mySearch').value;
And then use this value in your api url.

Why is my for loop not working in my JSON function?

Hey Guys im new at coding and working right now on a Twitch Viewer. (FreeCodeCamp)
Im able to get information from the JSON file and show it through my html code.
But my problem is that i cant get the names from my "gamer" array.
Why is the for loop not working in the json function?
Thank you very much for your help!
var gamer = ["OgamingSC2","ESL_SC2"];
for(i=0;i<(2);i++){
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[i]+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer[i] + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
console.log(json);
});}
img {
width: 5em;
border-radius: 10px;
}
<head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head>
<body>
<b>Twitch.tv JSON API</b> </br>
<div class="list"></div>
</body>
What happens here is the $.getJson is an asynchronous call, which means that it will execute only after all of the sync operations are executed. So, the for loop runs twice, and two getJSON callback functions are added to the function stack.
Now as Javascript has lexical or functional scope, the variable i lives on in the global scope as 2 (as the final i++ also has executed).
Next, the callback functions are executed one by one off of the function stack. But alas, your variable i is now 2! Now the callback functions would only see gamer[2] which doesn't exist and this throws an undefined
If you add a console.log(i) to your $.getJSON, you'll see that it outputs only 2 two times.
Why don't you try this:
var gamer = ["OgamingSC2","ESL_SC2"];
gamer.map(function(gamer) {
loopIt(gamer);
});
function loopIt(gamer) {
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head>
<body>
<b>Twitch.tv JSON API</b> </br>
<div class="list"></div>
</body>
i think it json gives nothing because you put callback=?
when you pass ? in call back variable it take value with ? and gives nothing.
so just put callback= .dont give any values and try again. and just alert json variable in function. you will know value is coming or not. i dont found nothing wrong with loop and json link.
For this types of server call in for loop , you can use custom loop.
Like this, https://jsfiddle.net/s8eLhxpx/
var gamer = ["OgamingSC2","ESL_SC2"];
var initCounter = 0;
callServerData()
function callServerData(){
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[ initCounter ]+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer[ initCounter ] + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
console.log(json);
initCounter++
if(initCounter < gamer.length){
callServerData();
}
});
}

Uncaught ReferenceError: is not defined onclick when using character strings

I am trying to pass a variable to the onClick function using a previously stored value. I have a database setup that searches for store locations when provided with a ZIP code. For example, the following link is generated using an ajax call after a user searches for a Zip Code. The returned value "WAFHOH3" is the ID that is associated with that particular store:
Generated Link:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Based on this code:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
My problem is that if anything other than a number is returned I get a "Uncaught ReferenceError: WAFHOH3 is not defined" console error. When a number is passed like the example below, everything works fine and I get no errors and the application continues to work as expected.
For example (This Works):
Ive tried manually changing the character string to numbers only to isolate any database related issues. My only guess is that there is something in my code that is maybe attempting to verify the input as number.
The full code is below for the ajax call.
Full Code:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at admin#admin.com for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at admin#admin.com for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
You need to wrap the input item.store_code with quotation marks; otherwise, it tries to treat it as a variable, not a string:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Ideally, you would attach a click handler after giving the buttons a class (such as register):
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
I may be late, and maybe its an absolute mistake of me, but, i have to add my answer here because i just solved exactly the same situation in about three minutes ago .
I just solved this using the most simple sollution, and the error "Uncaught ReferenceError" from the console is solved, also i have my alert(); passing the variable as i needed.
I also need to include that i did not aproove the sollution gave, about "not using" the alert function, once i searched for the sollution, not for another method for that .
So, as i am using php, and the document is html, i thinked about the apostrophe charactere to the variable, after i had been spectating the element using chrome, first moving the function alert to the parent and child elements, that not solved .
After, also in the specting element, inside chrome F12 i tryed changing the function, including '' (that i passed in php code) into variable inside the alert function as: onclick="alert(variable);" to onclick="alert('variable');" and my alert had worked .
Ok. So, i try everything to insert '' 2 single quotes '' to my variable in php, that seems impossible, even if i change all my code to " and use ' or the oposite .
Then, i decided to try the most obvious and old school method, that is about charactere representation, and i cfound that ' (single quote) is represented by ' in php. Everything inside ->> ' <<-
My php code is like this : onclick="alert(&#039'.$variable.'&#039);"
It will work! (with no Vue), ok ? :)

Jribbble - How do I load 6 shots at a time

I'm a bit new to Javascript, but I've managed to get things to load to the page which is a start.
I'm trying to load 6 "shots" to a page with this script, but it currently loads them all:
<script type="text/javascript">
$(document).ready(function getDribbbleShots() {
$.jribbble.getShotsByPlayerId('abenjamin765', function (playerShots) {
var html = [];
$.each(playerShots.shots, function (i, shot) {
var str = (''+shot.description+'');
html.push('<div class="col-md-4"><div class="thumbnail"><a href="' +shot.image_url+ '" target="_blank">');
html.push('<img class="shot-image" src="' + shot.image_url + '" ');
html.push('alt="' + shot.title + '"></a>');
//html.push('<div class="caption"><h4>'+ shot.title +'</h4>');
//html.push('<div class="ellipsis">'+shot.description+'</div>');
html.push('<p class="imgTitle">' + shot.title + '</p></div></div></div>');
});
$('.dribbble-feed').html(html.join(''));
//$( ".ellipsis p" ).addClass( "ellipsis" );
}, {page: 1, per_page: 9});
});
</script>
I also I want to introduce a "load more" button that will load 3 shots at a time.
Any help would be greatly appreciated :)
Cheers
If you use playerShots.shots.slice(0, 2), the loop will go through just the first three "shots."
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
As far as loading more, you'll want to save the result from the API response to a variable accessible by your code that shows more "shots."

How can I display multiple (but seperate) JSON requests on the same page

I have a web page where I want to display hotel reviews from the yelp.com API for a number of hotels.
I have managed to do this for one hotel, and it works perfectly displaying the data under that specific hotel's details on the page. However, how can I now multiply this process so that I have separate reviews for each hotel?
My web page can be seen at http://dev.bhx-birmingham-airport.co.uk/pages/hotels.php to get an idea of what I'm trying to do.
The source code I am using so far looks like:
<script>
function showData(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>Review - ' + review.text_excerpt + ' Read more...</p>';
content += 'Rating - <img src="' + business.rating_img_url + '" />';
content += '<p>Date Added - ' + review.date + '</p>';
$(content).appendTo('#hilton');
});
});
}
$(document).ready(function(){
// note the use of the "callback" parameter
writeScriptTag( "http://api.yelp.com/business_review_search?"+
"term=hilton%20metropole"+
"&location=B26%203QJ"+
"&ywsid=[...]"+
"&callback=showData"); // <- callback
});
function writeScriptTag(path) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path);
document.body.appendChild(fileref);
}
</script>
Your question is somewhat unclear.
I assume that you want to send multiple requests to Yelp and have them processed by different callback functions.
You can do that by making a buildCallback method that takes information about the request to generate a callback for and returns a function.
You can then use an invocation of that function as the callback parameter, like this: callback=buildCallback('something') It will return a script that looks like this:
buildCallback('something')({"message: ... })
This code calls the buildCallback method, then calls the function that the buildCallback method returns.
For example:
(Assuming that each hotel has a <div class="HotelReviews" id="giveThisToYelp">)
function buildCallback(hotelName) {
return function(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>Review - ' + review.text_excerpt + ' Read more...</p>';
content += 'Rating - <img src="' + business.rating_img_url + '" />';
content += '<p>Date Added - ' + review.date + '</p>';
$(content).appendTo('#' + hotelName);
});
});
};
}
$(function() {
$('.HotelReviews').each(function() {
$.getScript("http://api.yelp.com/business_review_search?"+
"term=" + this.id +
"&location=B26%203QJ"+
"&ywsid=[...]"+
"&callback=buildCallback(" + this.id + ")"
);
});
});
Instead of inserting a script tag on the page with the request url and a callback function name, You should make multiple requests to Yelp services manually.
A simple example in JQuery:
function LoadReviews() {
for (var i = 0; i < myhotels.length; i++) {
$.getJSON("http://api.yelp.com/business_review_search?" + myhotels[i], null, showData);
}
}
Where the myhotels array contains the search parameters for each of your hotels.

Categories