A
A
Alex2016-07-21 20:54:33
YouTube
Alex, 2016-07-21 20:54:33

How to get statistics of YouTube channel views on the site?

I'm trying to get the number of views of a youtube channel on a site.
I need to associate an html tag <p id="youtubeRequest">1120</p>with a request so that instead of a manually entered number, I get the value of the request.
I added this code to my HTML right after this tag:

<script>
   function getViews(params) {
     $.ajax({
       // я заменяю {} на API key и ID здесь
       url: "https://www.googleapis.com/youtube/v3/channels?part=statistics&key={MY_API_KEY}&id={MY_CHANELL_ID}",

      jsonp: "callback",
      dataType: "jsonp",


      success: function(response) {
       console.log(response);
       document.getElementById("youtubeRequest").innerHTML = response;  // не знаю как назначить response
      },

      error: function(response) {
       document.getElementById("youtubeRequest").innerHTML = "nope, doesn't work!";
    }
   });
   }
</script>

I am using "browser API key". Deploying to hosting does not solve the problem (API key only works with *.mysite.com/*), the result is the same as on localhost. I imported https://ajax.googleapis.com/ajax/libs/jquery/2.2.2...
The code doesn't work and doesn't even give an error to the console, even if I replace it document.getElementByIdwith console.log("error") or alert ("error")
I don't know why this JS code doesn't work. How do I bind this youtube api request to this tag and make it work?
Thank you for your help. Especially, FireGM for the code example

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2016-07-21
@EvilGenius18

See how to make requests to api
https://developers.google.com/youtube/v3/docs/chan...
Making a request
Get apik
https://developers.google.com/youtube/v3/getting-s...
UPD:
Example with jQuery. In success, process and paste where necessary

function getViews(params) {
  $.ajax({
    url: "https://www.googleapis.com/youtube/v3/channels?part=statistics&key={YOUR_API_KEY}&id={YOUR_CHANELL_ID}",

    jsonp: "callback",
    dataType: "jsonp",

    success: function( response ) {

        console.log( response ); 
    }
});
}

UPD2:
<script>
   function getViews(params) {
     $.ajax({
       // я заменяю {} на API key и ID здесь
       url: "https://www.googleapis.com/youtube/v3/channels?part=statistics&key={MY_API_KEY}&id={MY_CHANELL_ID}",

      jsonp: "callback",
      dataType: "jsonp",


      success: function(response) {
       console.log(response);
       document.getElementById("youtubeRequest").innerHTML = response.items[0].statistics.viewCount;  // Брать только количество просмотров
      },

      error: function(response) {
       document.getElementById("youtubeRequest").innerHTML = "nope, doesn't work!";
    }
   });
   }
getViews() //<--Вызвать функцию!!!
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question