Function Not Defined OEmbed Vimeo API - javascript

Started messing around with Vimeo API in an attempt to create a clickable gallery like this (http://www.aideffectiveness.org/busanhlf4/vimeo/php-example.php). However, when I moved some of the code into a "script.js" file as a way to organize my code from the other parts of the site, the json callback keeps saying that the 'embedVideo' function is not defined. Any ideas?
The "script.js" file is placed at the bottom of the page and has the following:
var NS = NS || NS;
NS = {
videoInit: function() {
var oEmbedUrl = 'http://vimeo.com/api/oembed.json';
var oEmbedCallback = 'embedVideo';
var videoid = "";
if(videoid == '' ){
videoid = '23515961';
}
function embedVideo( video ) {
var videoEmbedCode = video.html;
document.getElementById('embed').innerHTML = unescape(videoEmbedCode);
}
function init() {
loadScript(oEmbedUrl + '?url=http://vimeo.com/' + videoid + '&height=380&width=700&callback=' + oEmbedCallback);
}
function loadScript( url ) {
var js = document.createElement('script');
js.setAttribute('src', url);
document.getElementsByTagName('head').item(0).appendChild(js);
}
init();
}
}
$(function() {
NS.videoInit();
});
The HTML:
<div id="wrapper">
<div id="embed"></div>
</div>

embedVideo is a local (private) function inside of the init method. Nothing outside it can see it. That's why your AJAX callback is throwing that error.
You can fix this by making embedVideo a proper method of NS, so that's it's visible to your ajax callback
NS = {
embedVideo: function( video ) {
var videoEmbedCode = video.html;
document.getElementById('embed').innerHTML = unescape(videoEmbedCode);
},
videoInit: function() {
var oEmbedUrl = 'http://vimeo.com/api/oembed.json';
var oEmbedCallback = 'embedVideo';
var videoid = "";
if(videoid == '' ){
videoid = '23515961';
}

Related

PHP / XMLHttpRequest POST HTML5 Worker Store json echo in variable

I see a lot of these questions comming by. But I seem to do something wrong. So forgive me for asking (I am a bit of a n00b). In my php I echo the the folowing echo json_encode(['msg'=>$NewTotal]);.
I use a HTML5 worker to post data to a php on my server and I need the echo to be posted back to the main script so I can repost it to set it as new value for the variable Totalaccounts for the loop.
Worker Script:
onmessage = function(dbs) {
console.log(dbs.data);
var Totalaccounts = dbs.data;
var DBScriptLoop = setInterval(
(function () {
DBStartWorking();
//postMessage(Totalaccounts);
}), 123000);
function DBStartWorking(){
for (var dw = 0; dw < Totalaccounts; dw++) {
setTimeout(function() {
httpRequest = new XMLHttpRequest()
var dataresponse = httpRequest.responseText;
var NewCount = dataresponse.msg;
httpRequest.open('POST', 'DostuffV1.php')
httpRequest.send(Totalaccounts)
postMessage(NewCount);
console.log(NewCount);
}, 1200 * dw);
}
} // End script loop
};
Main script:
var DBScriptWorker;
function startDBScriptWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(DBScriptWorker) == "undefined") {
DBScriptWorker = new Worker('DBScriptWorker.js');
var php_va = "<?php echo $AccToRank; ?>";
DBScriptWorker.postMessage(php_va);
}
DBScriptWorker.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
DBScriptWorker.postMessage(event.data);
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
}
}
function stopDBScriptWorker() {
DBScriptWorker.terminate();
DBScriptWorker = undefined;
}
In my network tab I see the response is this: {"msg":29}
My variable is not set, it commes up as undifined. What am I doing wrong? Searching and trying for hours now..

JSON get data form url using javascript and than save the data to a var [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
<script type="text/javascript">
$(document).ready(function() {
var chanName = "";
loadchannelID("Pewdiepie");
function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$('#ytID').html(data.items[0].id);
//MAKE IT TO A VAR
});
}
function loadChannel(data) {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url1, function(data){
$('#ytName').html(data.items[0].snippet.title);
$('#ytDis').html(data.items[0].snippet.description);
$('#ytImage').html(' <img class="img-circle" src=\"'+data.items[0].snippet.thumbnails.medium.url+'\" >');
});
}
setInterval( function() {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+chanName+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
}, 5000);
$('#update').click( function(){
loadchannelID($('#chnlName').val());
})
});
</script>
This is what is have done so far. I need to get the id form a Youtube channel but i have a Youtube name. So i need to convert the name to the youtube channel id. The "Function loadchannelID" is what i have so far, it works but i need to get the #ytID to a var. But I dont know how to do that. The other function is to show the data from the Channel ID and that will work aswell if the id is converted to a var. Please help! Thanks!
I hope this is what you want to achieve:
var chanName = "";
var chanID = 0;
loadchannelID("Pewdiepie");
function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
chanID = data.items[0].id;
$('#ytID').html(chanID);
loadChannel(chanID); // now, you know the ID, pass it to "loadChannel"
});
}
function loadChannel (id) {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url, function(data) {
$('#odometer').html(data.items[0].statistics.subscriberCount);
$('#viewCount').html(data.items[0].statistics.viewCount);
$('#commentCount').html(data.items[0].statistics.commentCount);
$('#videoCount').html(data.items[0].statistics.videoCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+id+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI';
$.getJSON(url1, function(data){
$('#ytName').html(data.items[0].snippet.title);
$('#ytDis').html(data.items[0].snippet.description);
$('#ytImage').html(' <img class="img-circle" src=\"'+data.items[0].snippet.thumbnails.medium.url+'\" >');
});
}
I am not clear if you are trying to get the value or you try to make the url but in both cases you can do:
if you want to get the param value you can use:
var url_string = "https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=Pewdiepie&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI";
var url = new URL(url_string);
var forUsername = url.searchParams.get("forUsername");
if you want to set the param you can do:
var forUsername = url.searchParams.set("forUsername", yourValueHere);
As ive already said, your code is async, so you may use Promises like this:
function loadchannelID(name){
return new Promise(function(resolve){
var chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$('#ytID').html(data.items[0].id);
//lets resolve the promise
resolve(data.items[0].id);
});
});
}
So you can use it like this:
loadChanelID("test").then(function(name){
alert("name is"+name);
});
If you change
function loadChannel(data) {
To:
function loadChannel(id){
You can do:
loadChanelID("test").then(loadChannel);
I assume you want to use your var within the class and chanName is your channel ID and name container array
(function($, jsYouTube){
var chanName = "";
$.getChannelID = function loadchannelID(name){
chanName = name;
var nameid= 'https://www.googleapis.com/youtube/v3/channels?part=id&forUsername='+name+'&key=AIzaSyCppVQFcUiLE8-Z2JSyjpvvek8WfPeCfcI'
$.getJSON(nameid, function(data) {
$this.chanName['id'] = data.items[0].id ;
});
}
})(jQuery, 'jsYouTube');

iFrame doesn't load src when initialized after HTML is rendered

So I have a page where I need to embed a youtube trailer in an iFrame, based on what movie/serie has been clicked in the view. For this I use the Youtube Search API.
Right now when the page is loaded, it first gets some data from another API, loads the Youtube API, and then gets the videoId of the trailer, and assigning it to a $scope variable in the view.
In the view I just got this bit of code:
<div class="row">
<iframe width="420" height="315" ng-src="{{video}}" frameborder="0" allowfullscreen></iframe>
</div>
And the controller looks like this:
var serieId = $routeParams.id;
$http.get("http://api.tvmaze.com/shows/" + serieId)
.success(function (data) {
console.log(data);
$scope.name = data.name;
$scope.img = data.image.medium;
$scope.rating = data.rating;
initYTAPI();
$http.get("http://api.tvmaze.com/shows/" + serieId + "/episodes")
.success(function (episodes) {
console.log(episodes);
$scope.episodes = episodes;
var maxSeason = 0;
for (var i = 0; i < episodes.length; i++) {
if (episodes[i].season > maxSeason) {
maxSeason = episodes[i].season
}
}
$scope.seasonCount = [];
for (var i = 1; i <= maxSeason; i++) {
$scope.seasonCount.push(i)
}
});
});
And the initYTAPI function:
gapi.client.setApiKey("MY_API_KEY");
gapi.client.load("youtube", "v3", function(){
//yt api is ready
console.log("Api ready");
var query = $scope.name + " Official Trailer";
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: query,
maxResults: 1
});
request.execute(function(response){
var base_URL = "https://www.youtube.com/embed/";
var url = base_URL + response.items[0].id.videoId;
url = $sce.trustAs($sce.RESOURCE_URL, url);
console.log(url);
$scope.video = url;
//Tried to do it with ng-bing-html aswell
//$scope.trailerHtml = "<iframe width=\"420\" height=\"315\" ng-src=\"url\" frameborder=\"0\" allowfullscreen></iframe>";
});
});
I've inspected the page with developers mode to see if the iFrame get loaded correctly, but it doesn't seem to contain any src (or ng-src) attribute.
I think it has something to do with the view rendering before the javascript gets executed, but I've tried to make a service where the url was already pre calculated, and get the url from there, but that didn't seem to help either.
All help would be appreciated!
Your scoped variable ($scope.video) is getting executed outside of Angular's event loop. You can either set a watch on $scope.video (BAD), or wrap your custom scope change in $scope.$apply():
request.execute(function(response){
var base_URL = "https://www.youtube.com/embed/";
var url = base_URL + response.items[0].id.videoId;
url = $sce.trustAs($sce.RESOURCE_URL, url);
console.log(url);
$scope.$apply(function(){
$scope.video = url;
});
Here's a quick read to better understand Angular 1.3's event loop.

Changing url using javascript and jquery

Hello there
I am developing a jQuery plugin that loads files through ajax. When user clicks on a button which is:
<button class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
When user clicks on button it generates following url:
http://localhost//plugins/ajaxLoad/index.html#ajax/Login
I want to change it to
http://localhost//plugins/ajaxLoad/index.html/ajax/Login
My javascript is:
(function ($) {
$.fn.ajaxLoad = function (options) {
var settings = $.extend({
fileUrl : 'null',
loadOn : '.em'
}, options);
$('[data-load="ajax"]').each(function(index, el) {
$(this).click(function () {
var file = $(this).attr('data-file');
var loadOn = $(this).attr('data-load-on');
var permission = $(this).attr("data-ask-permission");
settings.fileUrl = file;
settings.loadOn = loadOn;
if (permission == 'yes') {
var ask = confirm("Do you want to load file");
if (ask == true) {
$.fn.loadFile();
}
}else {
$.fn.loadFile();
}
});
});
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.split(".");
location.hash = a[0];
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
}(jQuery))
Can anyone tell me how to change url in jquery and Javascript.
You need to use history.pushstate() to do this.
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Have a look at this article on MDN for more details
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
This article gives some nice jQuery examples.
https://rosspenman.com/pushstate-jquery
Added another attribute title to button
<button data-title="login" class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
In Js (after $(this).click line):
var title = $(this).attr('data-title');
settings.title = title
Just replace
location.hash = a[0];
With
history.pushState('','',"?"+settings.title);
Change
location.hash = a[0];
to:
location.pathname += '/' + a[0];
Just replace the hash with a blank using .replace()
Example .
settings.fileUrl.replace('.' , ' ');
Updated above also
UPDATE :
Don't hash the URL
Example :
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.replace("." , "/");
location.href = a;
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}

Loading jQuery externally for a bookmarklet

I'm trying to write a bookmarklet that will capture some parameters from a URL and send that to a script (the url in the post is just a dummy atm).
The problem is, I try to include jQuery to the page so I can use a $.post later. When trying to run the bookmarklet I get the following error in the console:
Uncaught ReferenceError: $ is not defined
I can see the jQuery is succesfully appended by looking at the Elements tab in the browser. Any tips on how to solve this?
You can see the bookmarklet below:
javascript:
function appendScript() {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
head.appendChild(script);
}
appendScript();
function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
};
parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:#]*)(?::([^:#]*))?)?#)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:#]+:[^:#\/]*#)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:#]*)(?::([^:#]*))?)?#)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
couponCode = parseUri(window.location.search).queryKey['couponCode'];
customerId = parseUri(window.location.search).queryKey['customerId'];
function showModal() {
if (couponCode != null) {
alert("Here is your coupon. Make sure to use it at checkout!" + couponCode);
}
}
showModal();
function parakeetCommunicator() {
if (couponCode != null) {
console.log("Sending data to Parakeet...");
$.post( "http://test.com/datascript.go", { customerId: customerId, couponCode: couponCode })
.done(function( data ) {
console.log("Succesfully posted the coupon was viewed to Parakeet server.");
});
}
}
parakeetCommunicator();
Script is loaded asychronously, you could fix it using onload event of script e.g:
var script = document.createElement("script");
script.onload = parakeetCommunicator;
script.src = ...;
And remove other call to this method.
If you only need jQuery for relative ajax wrapper, you should be interrested in building your own jquery version to support only these methods, see: http://projects.jga.me/jquery-builder/

Categories