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
}
});
});
});
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
}
});
});
});
Share
Improve this question
asked Nov 10, 2012 at 13:20
Ronny vdbRonny vdb
2,4746 gold badges34 silver badges79 bronze badges
3 Answers
Reset to default 5According 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');
}
}
}
Here $videoId contain video id of yuotube url
public function checkVideoExists() {
$headers = get_headers('http://gdata.youtube./feeds/api/videos/' . $videoId);
if (!strpos($headers[0], '200')) {
echo "The YouTube video you entered does not exist";
return false;
}
}
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)