Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Youtube video title with v3 URL API in javascript w Ajax & JSON

I am only trying to fetch Youtube video's title. Can't seem to figure it. So far I have this:

     q = 'https://www.googleapis.com/youtube/v3/videos?id='+ itemId +'&key='+ ytApiKey +'&fields=items(snippet(channelId,title,categoryId))&part=snippet' ;

$.ajax({
      url: q, 
      dataType: "jsonp",
      success: function(data){
               alert(data.items[0].title);
               console.log(data.snippet.title);            
      },
      error: function(jqXHR, textStatus, errorThrown) {
          alert (textStatus, + ' | ' + errorThrown);
      }
  });

Thanks,

like image 508
Kamy D Avatar asked Jan 19 '15 06:01

Kamy D


2 Answers

I got it working using

https://www.googleapis.com/youtube/v3/videos?id=itemId&key=apiKey&fields=items(snippet(title))&part=snippet

and

alert(data.items[0].snippet.title);

So, not much wrong with the syntax! But I found that the problem was really in the backend when setting up the Google API's 'allowed referers'. With V3 API, you can select which referers the API should belong to, so others cannot simply steal your API and use it. So the API will work if the request is originated from the domain name/IP you specify. When I don't give it restrictions, the code works, but when I do enter my domain it fails! I entered .mydomainname.com/ , the same format as it was suggested, but it errors out somehow.. Now I've got figure out why.

like image 190
Kamy D Avatar answered Nov 07 '22 12:11

Kamy D


The following jquery code will fetch the title of the video.

$.ajax({
      url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key="+ apiKey + "&fields=items(snippet(title))&part=snippet", 
      dataType: "jsonp",
      success: function(data){
               console.log(data.items[0].snippet.title);           
      },
      error: function(jqXHR, textStatus, errorThrown) {
          alert (textStatus, + ' | ' + errorThrown);
      }
  });
like image 35
Ayush choubey Avatar answered Nov 07 '22 10:11

Ayush choubey