JavaScript: Can't figure out what's going wrong in my use of this API

In summary, the conversation discusses the struggle to get the first video to automatically play on a dynamic web page using Google's YT JS API. The problem lies in the callback function for creating the video player object and is caused by calling a function with a similar name to the API's playVideo() function.
  • #1
Jamin2112
986
12
I've been trying to use Google's YT JS API to build a dynamic web page that plays Youtube videos back-to-back, i.e. a personal playlist. Here's the documentation for the API: https://developers.google.com/youtube/js_api_reference

Right now I am struggling to get the first video to automatically play. Here is the relevant code, which I'll explain below.

Code:
	        this.playAll = function()
	        {
	            var vidtexts = document.getElementsByClassName('vidtxt');
	            for (var i = 0, j = vidtexts.length; i < j; ++i)
	            {
                   var thisid = vidtexts[i].value;
                   if (thisid.length > 0)
                   {
    	               var thisurl = "[PLAIN]http://www.youtube.com/v/"[/PLAIN]  + thisid + "?enablejsapi=1&playerapiid=ytplayer&version=3";                    
                       var atts = { id: "myytplayer" };
                       var params = { allowScriptAccess: "always" };
                       swfobject.embedSWF(thisurl, "playerdiv", "425", "356", "8", null, null, params, atts, this.playVid);
                   }
	            }
	        } 
	        this.playVid = function(e)
	        {
	            /* Callback function for swfobject.embedSWF(...), to play the video
	               if the flash player was loaded successfully. */
	            if (e.success)
	            {
                    /* https://developers.google.com/youtube/js_api_reference#GettingReference */
                        ytplayer = document.getElementById("myytplayer");
        	        ytplayer.playVideo();
	            }
	        }

The problem is happening on the lines

Code:
ytplayer = document.getElementById("myytplayer");
ytplayer.playVideo();

When I first call playAll (by pushing a button), my browser's JavaScript console gives me the error

Code:
undefined is not a function

The next time I call the function, there are no errors and the video starts playing, like it should. It is therefore my presumption that playVideo is getting called before ytplayer has been initialized. But that seems weird because getElementById is supposed to finish executing before the next line is executed. I think that maybe ytplayer is not done initializing. But note that this is inside the callback function for the creation of the video player object and inside an if statement that executes only if the video player was successfully created.

The lines

Code:
                       var atts = { id: "myytplayer" };
                       var params = { allowScriptAccess: "always" };
                       swfobject.embedSWF(thisurl, "playerdiv", "425", "356", "8", null, null, params, atts, this.playVid);

should have created the video player with an id of "myytplayer" by the time we've reached the problem lines.

Any ideas?
 
Last edited by a moderator:
Technology news on Phys.org
  • #2
It looks like you defined playVid as the function name and then call ytplayer.playVideo(); which results in 'undefined is not a function'.
 
  • #3
DavidSnider said:
It looks like you defined playVid as the function name and then call ytplayer.playVideo(); which results in 'undefined is not a function'.

I have a class with a member function playVid that in turn calls the playVideo() function from the API. I should probably not have chosen such a similar name.
 

1. Why am I getting an error when using this API in my JavaScript code?

There could be several reasons why you are getting an error when using an API in your JavaScript code. Some common reasons include incorrect API key or authorization, improper formatting of the API request, or outdated API documentation. It is important to carefully read the API documentation and troubleshoot your code to identify the specific issue causing the error.

2. How do I debug my code when using an API in JavaScript?

There are several ways to debug your code when using an API in JavaScript. You can use browser developer tools to check for any errors in the console, use console.log() statements to track the flow of your code, or use a tool like Postman to test your API requests and responses. It is also helpful to refer to the API documentation and compare your code to working examples.

3. What is the best way to handle errors when working with an API in JavaScript?

The best way to handle errors when working with an API in JavaScript is to use error handling techniques such as try-catch blocks. This allows you to catch any errors that may occur and handle them accordingly, such as displaying a user-friendly error message. It is also important to check for error codes in the API response and handle them appropriately in your code.

4. How do I know which API to use for my project in JavaScript?

Choosing the right API for your project in JavaScript depends on your specific needs and the available APIs in the market. It is important to research and compare different APIs based on factors such as functionality, pricing, and reliability. You can also consult with other developers or seek recommendations from online communities to help you make an informed decision.

5. Can I use multiple APIs in my JavaScript code?

Yes, you can use multiple APIs in your JavaScript code. In fact, combining multiple APIs can enhance the functionality and capabilities of your project. However, it is important to ensure that the APIs you are using are compatible with each other and that they do not cause conflicts in your code. It is also recommended to carefully manage and monitor your API usage to avoid exceeding any API limits or quotas.

Back
Top