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

How can I correctly parse nested JSON stored as a string within a property using JSON.parse()?

I am having trouble decoding the response from aws secretsmanager The data I received appears as follows: { "ARN": "arn:aws:secretsmanager:us-west-2:0000:secret:token-0000", "Name": "token", "VersionId&qu ...

Is there an easy method for sorting through JSON data with various criteria?

After receiving a response from my web service containing an array of objects, I am looking to filter the data based on various combinations of values. What is the most efficient way to do this without impacting the performance of my web service? Data: Th ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

Guide on altering the cursor icon during an AJAX operation within a JQuery dialog

When I have a JQuery dialog open and make some $.ajax calls, why can't I change the cursor? I want to display a progress cursor while the code is processing so that users can see that the action is still ongoing. However, even though I update the CSS ...

Problem with <meta> tag occurring when initial-scale is adjusted

Initially, in the index.html file: <meta name="viewport" content="width=device-width, initial-scale=1" /> I decided to modify it to: <meta name="viewport" content="width=device-width, initial-scale=2" /> ...

Simple method for converting pixel values to em units

I'm searching for a simple method to incorporate a line of code into one of my plugins in order to convert specific pixel values into em values. My project's layout requires the use of ems, and I'd prefer not to rely on external plugins for ...

What is the best location to initialize a fresh instance of the Firebase database?

Is the placement of const db = firebase.database() crucial in a cloud function script? For instance, in a file like index.ts where all my cloud functions are located, should I declare it at the top or within each individual function? const db = firebase. ...

Verify the occurrence of an element within an array inside of another array

Here is the scenario: const arr1 = [{id: 1},{id: 2}] const arr2 = [{id: 1},{id: 4},{id: 3}] I need to determine if elements in arr2 are present in arr1 or vice versa. This comparison needs to be done for each element in the array. The expected output sho ...

Tips for incorporating jQuery UI into Angular 6

No matter how many methods I have tried from StackOverflow, I cannot seem to get jquery-ui to work in my angular 6 component. Here's what I've attempted: I went ahead and ran npm install jquery jquery-ui to install both jquery and jquery-ui. ...

HTML / CSS / JavaScript Integrated Development Environment with Real-time Preview Window

As I've been exploring different options, I've noticed a small but impactful nuance. When working with jQuery or other UI tools, I really enjoy being able to see my changes instantly. While Adobe Dreamweaver's live view port offers this func ...

Implementing custom CSS styles to a component in real-time with ng-style

When I use an angularjs component to create stylized pictures, the style is not applied correctly on the first visit to a page (refreshing the page shows the correct style). The CSS that should be applied is generated dynamically based on the height and wi ...

Restrict the number of GET requests made using D3.js and the Twitter API

Currently, I have made adjustments to my D3.js chart by switching from mouseover/mouseout events to mousemove. While this change has caused several issues in the chart, the most significant one pertains to my GET statuses/show/:id requests. In the past, h ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

recording the results of a Node.js program in PHP using exec

I'm attempting to retrieve the output from my node.js script using PHP exec wrapped within an ajax call. I am able to make the call and receive some feedback, but I can't seem to capture the console.log output in the variable. This is how I exec ...

Utilizing AngularJS to Retrieve URL Parameters Within a Controller

I am attempting to retrieve URL parameters in my controller: Although I came across this example, I encountered an error that appears to be connected to the loading of necessary modules. app.controller('WidgetCtrl', ['$scope', '$ ...

I am encountering an issue with the useRef function not properly detecting visibility

I'm looking to incorporate a fade-in animation into my React div as I scroll and reach a specific section. Unfortunately, the useEffect function that is supposed to detect the scrolling behavior seems to be malfunctioning and I can't figure out w ...

Issue encountered during Heroku deployment: Failed to build React app. When attempting to push changes to Heroku, an unexpected end of input error was received instead of the expected result. This error occurred on an unidentified file at

Encountering a parsing error while attempting to deploy a React app on Heroku using git push heroku master. The app built successfully yesterday, but since then some media queries were added by another contributor to various .scss files. The primary error ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

ReactJS is making a controlled input of type text into an uncontrolled component with the help of a component transformation

I am encountering a situation where I fetch data from the server and set values in the state for controlled inputs. For example, if I have an input field with a value of this.state.name, I retrieve the name "Dave" from the server and set it in the state as ...