I'm trying to use youtube api to be able to search for videos through my site however, when ever I click on the search button nothing pop up.It does log what I have searched but no videos pop up. Help Please. I am currently running it on Cloud9. I did get the error that I am missing "}" but where it is tell me I am missing it, there is a bracket already there.
Here is the Java-script code :
// JavaScript File
$(function(){
console.log(part1)
var searchField = $('#query');
var icon = $('#search-btn');
console.log(data);
//Focus Event Handler
$(searchField).on('focus',function(){
console.log(part2)
$(this).animate({
width:'100%'
}, 400);
$(icon).animate({
right:'10px'
}, 400);
console.log(part3)
});
// Blur Event Handler
$(searchField).on('blur',function(){
console.log(part4)
$("#searchfield").val('');{
$(searchField).animate({
width:'45%'
},400, function(){});
console.log(part5)
$(searchField).animate({
right:'360px'
},400, function(){});
console.log(part6)
}
});
('#search-form').submit(function(e){
console.log(part7)
e.preventDefault();
});
})
function search(){
//Clear Results
console.log(part8)
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search",{
part:'snippet, id',
q: q,
type:'video'
key:" AIzaSyDjByBmG4PJdONQf2DZE_SBQHuhhoZGiHg "}
function(data){
console.log(part8)
var nextPageToken = data.nextPageToken;
var previousPageToken = data.previousPageToken;
/
/ Get OutPut
console.log(part9);
$.each(data.items, function(i, items){
console.log(part10)
// Get Output
var ouput =getOutput(item);
//Display Results
$('#results').append(output);
console.log(part11)
});
}
);
}
// Build OutPut
function getOutput(item){
console.log(data);
var videoID = item.id.videoID
var title = item.snippet.title;
var description = item.snippet.description;
var thumb = item.snippet.thumbnails.high.url;
var channelTitle = item.snippet.channelTitle;
var videoDate = item.snippet.publishedAt;
console.log(part12)
// Built Output String
var output ='<li>'+
'<div class="list-left">'+
'<img src="'+thumb+'">'+
'</div>'+
'<div class="list-right">'+
'<h3>'+title+'</h3>'+
'<small>By<span class="cTitle">'+channelTitle+'</span>on '+videoDate+'</small>'+
'<p>'+description+'</p>'+
'</div>'+
'</li>'+
'div class="clearfix"></div>'+
'';
return output;
}
Related
hey i am creating a app in which dynamic images should be download from the net but some cant able to download kindly check the code below and give some suggestion to download and also tell how to pass dynamic image link in social share plugin in ngcordova .
$
scope.downloadImage = function() {
$http.get('http://sabkideal.com/phpapi_/cashback.php').success(function(response) {
$scope.data = response;
for (var i=0 ;i <response.length; i++)
{
var url = response[i].image;
var deal = response[i].id;
//url showing the same url every time i click and not jumping to next statement when click on send image download .
console.log(deal);
console.log(url);
var filename = url.split("/").pop ;
console.log(filename);
var targetPath = encodeURI(cordova.file.dataDirectory + fileName);
console.log(targetPath);
var options = {};
var trustHosts = true;
}
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(
function(result) {
alert('Download success');
refreshMedia.refresh(targetPath);
},
function(err) {
alert('Error: ' + JSON.stringify(err));
},
function(progress) {
// progressing download...
})
});
}
I am fetching html from a website. I want to get specific html from that page not all how to get that? I have tried following;
before appending data to target below
container.html(data);
I want to do like data.find('.site-header').html(); and then do container.html(data);
How can I achieve that?
DEMO
HTML
<div id="target"></div>
Script
$(function () {
var container = $('#target');
var url = 'http://aamirshahzad.net';
$.getJSON("http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) +
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var data = filterData(data.results[0]);
container.html(data);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg).focus().effect('highlight', {
color: '#c00'
}, 1000);
}
});
});
function filterData(data) {
// filter all the nasties out
// no body tags
data = data.replace(/<?\/body[^>]*>/g, '');
// no linebreaks
data = data.replace(/[\r|\n]+/g, '');
// no comments
data = data.replace(/<--[\S\s]*?-->/g, '');
// no noscript blocks
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
// no script blocks
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
// no self closing scripts
data = data.replace(/<script.*\/>/, '');
// [... add as needed ...]
return data;
}
Quite simply;
container.html($(data).find('.site-header'));
Add this line after container.html(data);:
container.html(container.find(".site-header"));
Here is your updated JSFiddle
Using parse.com and JavaScript SDK.
- Section one shows a list of objects
- Section two lets the user select one of those objects and add to a modal box
- Section three saves the data to parse
What I'm unable to work out is how I can save the section 1 item.badgename and item.category to parse.
I've tried adding myBadge.set("category", badgename.toString()); to section 3, but I get a undefined error. i'm not sure how to define this before trying to save.
Really need some help and an example to follow.
3 -Saves the badge details to parse
var MyBadge = Parse.Object.extend("myBadges");
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var badgeselected = $('#badgeselect .go').attr("src");
$(document).ready(function() {
$("#send").click(function() {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#selectFriend').val();
var categorySelected = $('#category').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected); //got this working using .set
myBadge.set("Comment", uploadercomment); //got this working using .set
myBadge.set("category", categorySelected);
myBadge.set("SentTo", new Parse.User({
id: BadgeSentTo
}));
myBadge.set("uploadedBy", Parse.User.current());
myBadge.save(null, {
success: function(results) {
console.log("Done");
//location.reload();
},
error: function(contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
** 1- Returns results to the page for user to select**
var GlobalBadges = Parse.Object.extend("Global_Badges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badges_img");
query.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('Global_Badges_img'),
//friendRequestId: results[i].id,
badgename: results[i].get('BadgeName'),
category: results[i].get('category')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function(item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div id="name"class="tag badgelabel" >'+ item.badgename + '</div>'+ '<br>');
wrapper.append('<div id="category" class="tag categorylabel" >'+ item.category + '</div>'+ '<br>'+ '<br>' );
$('#container').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
2 -Upon the user selecting an object from above, this adds the data to a modalbox
$(document).ready(function() {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function(e) {
$('.go img').removeClass('BadgeImgOutline');
$(this).parent().appendTo('#badgeselect');
$(this).addClass('BadgeImgOutlineSmall');
$('.go img').addClass('BadgeImgOutline');
$('#modal').reveal({
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});
This was addressed by making the following changes.
- Taking the data from #badgeSelect not #category
- From section 3, the line var categorySelected = $('#category').val(); was changed to categorySelected = $('#badgeselect .categorylabel').text();
By taking the data from #badgeSelect it meant that the only data being available was that shown shown in the text box, instead of '#category'that returned all results.
The it was simply targeting the text correctly with the change to the var categorySelected
I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}
This is part of my youtube project. I try to extract video information from JSON format but I have problem in this line:
var videoId = data.feed.entry[i].link[1].href;
When I do this in single line not in cikle evrithing is ok but in cikle for or while I have error.
//get youtube ID
function extract(url){
pos1=url.indexOf("videos/");
pos2=url.substr(42,11);
return pos2;
}
//My playlist LINK
var url2="http://gdata.youtube.com/feeds/api/playlists/B2A4E1367126848D?v=2&alt=json";
function playlistinfo(url1) {
$.ajax({
url: url1,
dataType: "jsonp",
success: function (data) { parseresults(data); }
});
}
//whit this get playlist data
function parseresults(data) {
//return playlist clip number
var klipove= data.feed.openSearch$totalResults.$t;
//put clips in <li>
for(i=0;i<=klipove-1;i++) {
var videoId = data.feed.entry[i].link[1].href;
//get video id ID
var id= extract(videoId);
thumb = data.feed.entry[i].media$group.media$thumbnail[0].url;
$('<li><img src="'+thumb+'" alt="'+id+'" class="thumb"/></li>').appendTo('.cont');
}
}
IMHO, you code can be much shortened if you use $.getJSON, $.each
Try this.
var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/B2A4E1367126848D?v=2&alt=json&callback=?';
var videoURL= 'http://www.youtube.com/watch?v=';
$.getJSON(playListURL, function(data) {
var list_data="";
$.each(data.feed.entry, function(i, item) {
var feedTitle = item.title.$t;
var feedURL = item.link[1].href;
var fragments = feedURL.split("/");
var videoID = fragments[fragments.length - 2];
var url = videoURL + videoID;
var thumb = "http://img.youtube.com/vi/"+ videoID +"/default.jpg";
if (videoID !='videos') {
list_data += '<li><img alt="'+ feedTitle+'" src="'+ thumb +'"</li>';
}
});
$(list_data).appendTo(".cont");
});
Demo: Fiddle for the playlist you have provided
P.S: Keep in mind that thumbnail for a youtube video could be found at
http://img.youtube.com/vi/{video-id}/default.jpg
( More Info here )
I found that these lines:
var feedURL = item.link[1].href;
var fragments = feedURL.split("/");
var videoID = fragments[fragments.length - 2];
are expecting item.link[1].href to be in this format:
http://gdata.youtube.com/feeds/api/videos/NAs5it-xjnQ/responses?v=2
However, it does not necessarily work as sometimes item.link[1] gives an URL like
http://www.youtube.com/watch?v=Vcp7xz6dfWE&feature=youtube_gdata
Fragments[fragments.length - 2] will end up being "www.youtube.com" instead of the video ID.
I modified it to retrieve the link from item.content.src which always has a fixed format in the URL e.g.
http://www.youtube.com/v/NAs5it-xjnQ?version=3&f=playlists&app=youtube_gdata
So the final code snippet is something like:
var tmp = item.content.src.split("/").reverse()[0];
var videoID = tmp.substring(0, tmp.indexOf("?"));
which so far has not failed me yet.
Hope this helps those who are stuck or is having problems retrieving the video ID.
Regards
CK
Simplified the solution and got rid of the string manipulation stuff.
var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/B2A4E1367126848D?v=2&alt=json&callback=?';
var videoURL= 'http://www.youtube.com/watch?v=';
var vids = new Array();
$.getJSON(playListURL, function(data) {
$.each(data.feed.entry, function(i, item) {
vids.push( item["media$group"]["yt$videoid"]["$t"] );
});
console.log( vids );
});