How to display YouTube video by pasting its URL in text box? This is what I have done using PHP and Ajax. I will explain in simple way. Place a text box and write Ajax code to pass the YouTube URL to PHP script. PHP script will process and passes the embed code back to Ajax and Ajax will display the content in DIV container. That’s it.
HTML file
PHP file
Want to test on your local xampp server here is the zip file link Download rar file
HTML file
<body onload="text = document.getElementById('url');text.focus();" style="text-align:center;background-color:white;color:grey;">
<script>
function url(){
//taking text field value into variable
url = document.getElementById('url').value;
//checking if value is empty
if(url ==""){
//then do nothing
return 0;
}
//taking 0 to 23 characters from YouTube URL
yurl = url.substring(0,23);
//checking those 23 characters with string
if(yurl =='https://www.youtube.com' || yurl =='http://www.youtube.com/'){
//Ajax starts here
//checking if browser is internet explorer
if(navigator.appName=="Microsoft Internet Explorer"){
//creating object for Internet Explorer
obj = new ActiveXObject("Msxml2.XMLHTTP");
}else{
//creating object for Firefox and other browsers
obj=new XMLHttpRequest();
}
//opening connection passing url variable to PHP script
obj.open("GET","youtube.php?"+url,true);
obj.send();
obj.onreadystatechange=function(){
//if readystate is completed ie 4 get the PHP script
if(obj.readyState==4){
//get the Div tag
div = document.getElementById("preview");
//place the content we got from PHP script in Div tag
div.innerHTML=obj.responseText;
}}
}
else{
alert("Please enter youtube url");
}
}
</script>
<div style="margin-top:130px;">
Enter YouTube URL <input type="text" name="url" size="50" id="url" onblur="url()">
<div id="preview" style="padding-top:20px;"></div>
</div>
</body>
PHP file
<?php
if(isset($_SERVER['QUERY_STRING'])){
//capture the url variable and store it in $url
$url = $_SERVER['QUERY_STRING'];
//divide the url we got into 2 parts using "=" sign
$text = explode("=",$url);
//take the second part
$value = $text[1];
//add that value to YouTube embed code
$t=<<<str
<iframe width="560" height="315" src="//www.youtube.com/embed/$value" frameborder="0" allowfullscreen></iframe>
str;
//display YouTube embed code with value
echo $t;
}
?>
Want to test on your local xampp server here is the zip file link Download rar file