Facebook like fetch YouTube embed videos from url using PHP and Ajax - Mostlikers

04 November, 2015

Facebook like fetch YouTube embed videos from url using PHP and Ajax

Have you shared YouTube video url in facebook timeline.  while typing the link YouTube video will preview the timeline. I had developed Facebook like fetch YouTube embed videos from url using PHP and Ajax with live demo. 

Facebook like fetch YouTube embed videos from url using PHP and Ajax


Live Demo          Download

Html and Javascript

on('keyup','#you_url',function(){}- search input id .The keyup event is sent to an element when the user releases a key on the keyboard.
$("form")[0].checkValidity() - Checking url validation. 
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).on('keyup','#you_url',function(){
  var url = "ajax.php";       
  if($("form")[0].checkValidity()) {
    var youtube = $("#you_url").val();
    $('#ajax_result').html('Please wait...');
    var dataString = 'youtube=' + youtube;  
    $.ajax({
    type: "POST",
    url: url,
    data: dataString, 
    success: function(data)
    {
        $('#ajax_result').html(data);
    }
    });
  }      
  return false;
});
</script>   
</head>
<body>
    <input name="youtube"  pattern="https?://.+" required id="you_url" type="url">  
    <div id="ajax_result"></div>
</body>
</html>

ajax.php

preg_match - Perform a regular expression match. Check with valid url data (youtu.be,youtube,com). Sucess data will append <div id="ajax_result"></div>
<?php
if(isset($_POST['youtube'])) :
 $url =$_POST['youtube'];
if(preg_match("/youtu.be\/[a-z1-9.-_]+/", $url)) {
    preg_match("/youtu.be\/([a-z1-9.-_]+)/", $url, $check);
    if(isset($check[1])) {
        $url = 'http://www.youtube.com/embed/'.$check[1];    
        echo '<iframe width="580" height="289" src="'.$url.'" ></iframe>';
    }
}
else if(preg_match("/youtube.com(.+)v=([^&]+)/", $url)) {
    preg_match("/v=([^&]+)/", $url, $check);
    if(isset($check[1])) {
        $url = 'http://www.youtube.com/embed/'.$check[1];
        echo '<iframe width="580" height="289" src="'.$url.'"></iframe>';
    }
}
else
{
    echo 'Wrong url';
} 
endif;
 ?> 


CSS

<style type="text/css">
    #you_url
    {
        width: 500px; height:50px;
    }
</style>

Have a Question? Share your query by writing a comment below.

"Excellence is a continuous process and not an accident."
                                             
                                         - A. P. J. Abdul Kalam








Related Topics

No comments:

Post a Comment