How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id.

Here is the code snippet I've written:

var vidID = "";

var vidData;

var vidDuration;

function getResponse() {
  $.getJSON( "https://www.googleapis.com/youtube/v3/videos?id=unSlPx7Zu-w&part=contentDetails&key=AIzaSyCSMBWe5CbW122szJGvGjQ6UrktPL4Z0Mw", function( data ) {
    var items = [];
    
    vidDuration = data;
    
    $.each( data, function( key, val ) {
      items.push( "<li id='" + key + "'>" + val + "</li>" );
    });
    
    $('body').append (JSON.stringify(data));
    
    $( "<ul/>", {
      "class": "my-new-list",
      html: items.join( "" )
    }).appendTo( "body" );
  });
}

getResponse();

console.log(vidDuration.items[0][contentDetails][duration]);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js"></script>
</body>
</html>

Console Results:

"error"
"TypeError: Cannot read property 'items' of undefined
    at felepivuni.js:28:50
    at https://static.jsbin.com/js/prod/runner-4.1.4.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.4.min.js:1:10866"

The script seems to be functioning correctly as it provides the expected output of stringified JSON and two main JSON objects.

However, there are issues with displaying '[Object object]' twice in the result.

This is the structure of the response packet we receive:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
 "items": [
  {

   "id": "9bZkp7q19f0",
   "kind": "youtube#video",
   "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
   "contentDetails": {
    "duration": "PT4M13S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true,
    "regionRestriction": {
     "blocked": [
      "DE"
     ]
    }
   }
  }
 ]
}

Despite encountering similar issues before, my efforts remain unsuccessful in rectifying the problem.

Upon running the code, the console logs undefined, and the resultant output displays [Object object], which was anticipated.

Although resources like the Youtube Video Duration API v3 exist, they haven't provided solutions to my specific issue.

Your insights into why the code isn't producing the desired outcome would be greatly valued!

Thank you!

  • Noah

Answer №1

Remember, the $getJson function is asynchronous in nature.

Make sure to wait for the getResponse() function to complete its execution before proceeding further.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue involving interface implementation (#6634) when transitioning from legacy code to Fortran 90/95

After spending a considerable amount of time working with a scientific software for mechanical analysis, I found myself dealing with code that originated in the eighties (Fortran 77) and has since evolved into a hybrid form of Fortran 90/95. To enhance the ...

Exploring the process of sending various variables from PHP to a jQuery function

I have a jQuery function that prints charts using the jqPlot framework. I need to print multiple charts with different options, so I have to call this function several times with varying values. My current approach is not very elegant: //----- index.php: ...

Generate inputs from terminal and store them in a collection

Is there a way to save command line arguments and their parameters in separate arrays without knowing the number of ":" used? For example: ./run cat hello.txt : grep left : wc -c I want to divide each argument into an array, like: char *cat_args[] = {"ca ...

the counterpart of jQuery.active in vanilla JavaScript

Is there a way to monitor the active Ajax requests on a non-jQuery site? I'm looking for an equivalent to jQuery.active. I am interested in checking if all the ajax requests have been completed after loading a page. I came across the window.XMLHttpR ...

Ways to choose an option from a drop-down menu without the select tag using Selenium

I'm looking to perform automated testing with Selenium using Java but I'm facing an issue when trying to select an item from a dropdown list. The HTML structure does not include a select tag for the drop-down menu items (such as Auth ID and Corre ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...

When working with React JS and the react-select library, I am looking to automatically reset the options to their default value once

I am attempting to disable the select list after unchecking the checkbox and resetting the select value back to default, but currently it is retaining the last selected option. I am utilizing React-select for the select and options in this scenario. APP.j ...

HTML5 input type Color displays individual RGB values

This code snippet opens up a variety of options for the user to manipulate different color values such as R, G, B, HEX VALUE, HUE, etc. However, the specific requirement is to only extract the Red value. <input id="color_pick"type="color" value="#ff0 ...

Asynchronous function nested within a loop

Hello there! I am currently working on converting a SQLite database to NeDb using the following code snippet: const sqliteJSON = require('sqlite-json'); const Datastore = require('nedb') const exporter = sqliteJSON('etecsa.db&apo ...

The functionality of GET_POST is not functioning properly

I've encountered an issue with my PHP webpage and JavaScript function: function send_answer(){ $.ajax({ type: 'POST', url: '../path2file/file_mine.php', data: {dbf1:1, us:1, re:1}, success: relo ...

router.query is returning an empty object when using Next.js

Here is how my folders are organized: https://i.stack.imgur.com/TfBtv.png In addition, here is a snippet of my code: const router = useRouter(); const { id } = router.query; The issue I'm facing is that the id is returning {} instead of the actual ...

The screen-responsive navigation bar is experiencing functionality issues

I am facing an issue with my navigation bar on both desktop and mobile. When I maximize the window while the mobile navbar is open, it disappears as expected but the desktop navbar does not appear. I am using a bootstrap template and I am unsure if solving ...

Creating a CSV download feature with ReactJS is simple and incredibly useful. Enable users

Despite searching through various posts on this topic, I have yet to find a solution that addresses my specific issue. I've experimented with different libraries and combinations of them in an attempt to achieve the desired outcome, but so far, I have ...

Is it possible to organize multiple tables within a single JSON structure without relying on JArray?

I am currently developing a program similar to IMDB, where I am showcasing individuals with a filmography, discography, and more. After setting up my view in MVVM, I am now working on serializing my JSON data to align with it. At the moment, I am consolida ...

Which one entered the scene first: IBAction or ViewDidLoad?

In my app, there is a Button on the First View Controller that can lead to two different active states. 1) SecondVC override func viewDidLoad() { super.viewDidLoad() subjectPickerView.dataSource = self subjectPickerView.delegate = self S ...

What methods can I implement to ensure a button illuminates only when correct information is provided?

I have developed a calculator for permutations and combinations. When either permutation or combination is selected, and the required values are entered, I want the calculate button to light up. How can I achieve this without using setInterval in my curren ...

Steps for embedding JavaScript code within HTML tags using a JavaScript file

Working on a React web app, I am solely using js and css files without any html. In one of my js files, there is a mix of html and js code like this: class Teams extends Component { state = { teams: [] } componentDidMount() { ...

Decoding JSON Data on Android

I am relatively new to utilizing web services in Android development, and I am currently facing an issue with parsing JSON data from a URL. Below is my code snippet: JSONParser.java import java.io.BufferedReader; import java.io.IOException; import java.i ...

Tips for retrieving values from numerous checkboxes sharing the same class using jQuery

Currently, I am struggling with getting the values of all checkboxes that are checked using jquery. My goal is to store these values in an array, but I am encountering difficulties. Can anyone provide me with guidance on how to achieve this? Below is what ...

The failure of jQuery AJAX error callback to execute

I'm currently facing an issue with an AJAX call that I have in my code. Here's the code snippet: $.ajax({ type: "get", url: "xxx.xxx.xxx/xxx.js", dataType: 'jsonp', success: function(data) { ...