I am working on a simple page that has a text input where the user can add the id of the youtube video they want to insert into the page, then I call youtube's iframe api to load the video. However, if the user adds an id that does not exists I get a black screen.
I was hoping someone knows a way of checking if the video exists before loading it.
This is my code:
$(document).ready(function() {
$('#loadVid').click(function() {
var player;
var urlVid = $('#urlVid').val(); //GET THE VIDEO CODE FROM THE TEXT INPUT
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: urlVid,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
});
Here $videoId contain video id of yuotube url
public function checkVideoExists() {
$headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $videoId);
if (!strpos($headers[0], '200')) {
echo "The YouTube video you entered does not exist";
return false;
}
}
According to the documentation the onError should give you such info
100 – The video requested was not found. This error occurs when a
video has been removed (for any reason) or has been marked as private.
Add the onError event handler to the events object
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': function(errEvent) {
var errCode = errEvent.data;
if(errCode == 100) {
alert('Video Not Found');
}
}
}
Just trigger a test Ajax request to the URL before opening the player. If the Youtube page video does not exist, it returns a 404 header (I've just tested this with a non-existing video URL).
If you use the $.ajax method, you could insert the player loading function in the success callback, and trigger an error alert in the error callback (as it should be called if the response headers are 4xx or 5xx)