Youtube API loadVideoByUrl() function - javascript

I've got this code, which add videos (and videos infos) of a YouTube channel ($_POST) on a div of the Html code, and I want to play a video in the Youtube player after click on an element:
var args= "url="+urlchaine;
xhr_object.open("POST", "traitement.php", true);
xhr_object.onreadystatechange = function() {
if(xhr_object.readyState == 4) {
eval(xhr_object.responseText);
}
return xhr_object.readyState;
}
xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr_object.send(args);
traitement.php :
<?php
if ( isset($_POST["url"]) && !empty($_POST["url"]) )
$urlchaine = $_POST["url"];
else
$urlchaine = null;
$stringresult = str_replace("http://www.youtube.com/user/", "",$urlchaine);
require_once "Zend/Loader.php";
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
$videoFeed = $yt->getVideoFeed('http://gdata.youtube.com/feeds/users/...');
if ( $stringresult != null){
echo "var mydiv = document.getElementById('vids');";
echo "var newcontent = document.createElement('div');";
foreach ($videoFeed as $v): $thumbs = $v->getVideoThumbnails();
echo "newcontent.innerHTML = '...'";
echo "mydiv.appendChild(newcontent.firstChild);";
endforeach;
echo "img_videos.addEventListener('click',function () {
$('#ytplayer_footer').fadeIn('normal');
var idvideo = this.getAttribute('idvideo');
var ytplayer = document.getElementById('ytplayer');
ytplayer.loadVideoByUrl('...'); // ****** Here the problem
ytplayer.playVideo();
},false);";
?>
And I have this error : Object # has no method 'loadVideoByUrl'
What's wrong in my code ?

You might have some quote escaping issues going on here. Take a look at this line:
var ytplayer = document.getElementById("ytplayer");
You're using double quotes, but your "echo" statement also uses double quotes. Switch that to single quotes and see what happens. I'm somewhat surprised this code runs at all.
(Looks like the question was changed)
The other thing to look out for is that you don't seem to be loading the YouTube JS anywhere. You're loading the PHP client library which runs server-side, but you also need to load the JavaScript libraries client side - otherwise you're just trying to call "loadVideoByUrl()" on a vanilla DOM object.

Related

How can JScript pull from my SQL DB to save repeating my code?

For my own reasons I am using JS in a seperate script, linked into my PHP file to perform several of nearly the same function (only the images change in each function) like this:
function Clicky1(element) {
var XTag= element.parentElement.previousElementSibling.firstChild;
if (element.src == "../image1.jpg")
{
element.src = "../image2.jpg";
XTag.innerHTML = XText;
localStorage.setItem(XTag.id, XText);
}
else
{
element.src = "../image1.jpg";
XTag.innerHTML = " ";
localStorage.removeItem(XTag.id);
}
}
function Clicky2(element) {
var VTag= element.parentElement.previousElementSibling.firstChild;
if (element.src == "../image3.jpg")
{
element.src = "../image4.jpg";
VTag.innerHTML = VText;
localStorage.setItem(VTag.id, VText);
}
else
{
element.src = "../image3.jpg";
VTag.innerHTML = " ";
localStorage.removeItem(VTag.id);
}
} //this repeats 3 more times
But what I want is to just use something like "{$myDB['images']}" as all the images that I am manually inserting links to within each function are already stored in my database. - How do I go about doing this in the simplest way?
You can't just inject PHP code into your Javascript like that. If the Javascript is in a block within a .php file then you can inject the result of running some PHP code as hard-coded values into your script, but not if it's in a separate .js file, because it doesn't pass through the PHP script engine before being sent to the browser.
But this code is overly repetitive anyway - why not have the image paths as parameters to the function? Then you could only have one single re-usable function. Apart from those names, the code is identical in its functionality. And also if these functions are called from JavaScript within a .php file, then you could inject the image paths into it using PHP at that point.
You'd change the function to more like this:
function Clicky(element, img1, img2) {
var XTag= element.parentElement.previousElementSibling.firstChild;
if (element.src == img1) {
element.src = img2; XTag.innerHTML = XText;
localStorage.setItem(XTag.id, XText);
}
else {
element.src = img1;
XTag.innerHTML = " ";
localStorage.removeItem(XTag.id);
}
}
And then you could call it from a <script block embedded in a PHP file, something like this:
Clicky(someElement, "<?php echo $myDB['images']; ?>", "<?php echo $myDB['images1']; ?>");
(or whatever PHP you have to use to get to each separate image string). Then you can use the values from your PHP easily, and you also wouldn't need Clicky1, Clicky2, Clicky3 etc etc all with virtually-identical code in them.

Passing Javascript variable to php on the same page

I'm trying to pass a javascript variable to php on the same page. I tried some code but nothing worked.
The current code looks like this:
function init(e){
$('#DeleteDaily').click(function() {
d = document.getElementById("DailyRequestsList");
selected = d.selectedIndex;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "index.php?i=" + selected, true);
xhttp.send();
});
}
$(document).ready(init);
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}
?>
});
});
If I try to use Index as an argument for a python script it should delete an entry in a textfile and an element from a select object should be deleted on the website which doesn't happen. The python script itself works fine.
But I don't know why the variable isn't passed to php.
You can't just "mix" javascript and PHP like you're doing.
If that is inside a web page, the PHP code will be rendered (in your case, it will return nothing), and the page will just interpret an empty javascript function.
You need that PHP to be on the server, or turn it into javascript...
you can done it by
PHP Code
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}else{
$Index='';
}
?>
Javascript code
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
var index = '<?php echo $Index;?>';
if(index == ''){
//put your code
}else{
//put your code
}
});
});

Send a string from javascript to php (in the same file)

So basically, I got a php file where I create a script in the header.
In this script, I take the value of two textbox with document.getElementByID and I concatenate them in a variable. But now, in the same script, I want to send that var to a php section to use it.
I tried the ajax way, but since the php and the javascript is in the same file, it make an error.
Here is what the script section looks like :
IN FILE.PHP
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
<?php
$parameter = command; <----- obviously not working, but that's basically what im looking for
$output = exec("someExecutable.exe $parameter");
(...)
?>
}
</script>
EDIT 1
So here it is, I tried to use ajax this time, but this isn't working, seems like i miss something. Here is the server.php:
<?php
$parameter = $_POST['command'];
$output = exec("someexecutable.exe $parameter");
$output_array = preg_split("/[\n]+/", $output);
print_r($parameter);
?>
And here is my ajax call in my client.php (in a js script):
var command = "find";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
var ajax = new XMLHttpRequest;
ajax.open("POST", "server.php", true);
ajax.send(command);
var output_array = ajax.responseText;
alert(output_array);
For some reason, it doesn't go farther then the ajax.open step. On the debugger console of IE10, i got this error : SCRIPT438: Object doesn't support property or method 'open' .
You are trying to run a serverside script in your ClientSide script,
that's never going to work.
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
If you want to do something with the data from text_1 and text_2, you should create a php file that can handle a post/get request via AJAX or a simple submit, featuring the data from those elements, and make it return or do whatever it is you want it to end up doing.
You can't use javascript variable (client) from php (server). To do that, you must call ajax.
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
//AJAX call to a php file on server
//below is example
var ajax = window.XMLHttpRequest;
ajax.open("POST", "yourhost.com/execute.php", true);
ajax.send(command);
}
</script>
And this is execute.php on server
<?php
$parameter = $_POST['command'];
$output = exec("someExecutable.exe $parameter");
(...)
?>
Alright... I pretty much changed and tested many things and I found out that the problem was the async property of the .send command. I was checking the value of the respondText too fast. Putting the third property of .open to false made the communication sync, so I receive the infos properly. I got another problem right now, but its not the same thing, so I will do another post.

how to send javascript variable to php mysql [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to insert javascript varaible to php mysql, but it is not inserting. it is inserting as <javascript>document.write(window.outerWidth); </javascript> x <javascript>document.write(window.outerHeight); </javascript>. but the result is 1366 x 728
What should I do?
<?php
$width = " <script>document.write(window.outerWidth); </script>";
$height = " <script>document.write(window.outerHeight); </script>";
$xex = " x ";
$resulteee = "$width $xex $height";
echo $resulteee;
?>
AJAX is a good solution to your problem :
<script type="text/javascript">
function call_ajax () {
var width = window.outerWidth;
var height = window.outerHeight;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("abc").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "a.php?height="+height+"width="+width, true);
xmlhttp.send();
}
</script>
and on the page a.php, you can echo your variables to get the output like this :
<?php
echo $_POST['height'];
echo $_POST['width'];
die;
The best way is AJAX, which is a way for Javascript to send data to a PHP script. You should do some research on your own, but your solution will end up looking something like this. I'm using jQuery syntax, which is a really helpful Javascript library that I recommend looking into.
// get values we want
var width = window.outerWidth;
var height = window.outerHeight;
var payload = {"width" : width, "height" : height}; // just a normal object
// send them to server
$.get('/path/to/script.php', payload, function(response) {
alert('Sent the values!');
});
And in your PHP:
<?php
$width = $_GET['width'];
$height = $_GET['height];
/*
* DEFINITELY sanitize these things before they're anywhere NEAR the database!
* research "prepared statements" and "mysqli escape" or you are going to have a very bad time with a hacked server
*/
// do some database stuff!
Hopefully this gives you a good starting point. You really need to make sure you sanitize data before you blindly let it touch a database query or attackers can easily perform a SQL Injection attack, deleting your database or dumping all your data. These are very bad things.
You'll have to send it to a separate php file to insert it into MySQL... You'll also have to use Ajax. Include the jquery plugin in your page for that.
So this would include this in your main page. Call the submitstuff() function when the button is pushed instead of submitting a form like normal:
<script>
function submitstuff(){
var wheight = window.outerHeight;
var wwidth = window.outerWidth;
var results = wwidth+" x "+wheight;
$.ajax({
url : "submit.php",
type: "POST",
data : "result="+results,
});
}
</script>
Then, make a file called submit.php and put it in the same folder as your main file.
submit.php
/* include all your database connection stuff */
mysql_query("insert into `yourtable` (`size`) values ('".$_POST['result']."');");
I didn't test this, but I think it might work... :)
Try jQuery's $.post
var width = x;
var height = y;
$.post( "page.php", // name of the page you want to send the variables
{width:width,height:height}, // variables
function( data ) { // returned values from the page
alert(data);
}
);
You can get the variables using $_POST['width'] and $_POST['height'].

defined path from php to javascript

I have a little problem with the syntax in Javascript. I want to work with a defined variable for a path in Javascript.
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "http://localhost:8888/.../file.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Now I want to set for
http://localhost:8888/.../file.php
a defined variable from php
define('Name','http://localhost:8888/.../file.php');
You'd either have to retrieve that constant via an AJAX call, or embed it into the Javascript at the time PHP is building the page.
e.g.
<?php
define('your_url', 'http://.....');
?>
<script type="text/javascript">
var url = <?php echo json_encode(your_url) ?>;
...
var ajax = ajaxOBJ('POST', url);
Note that if the sole purpose of this constant is to hold a url that's passed to javascript and is otherwise never used in PHP, you might as well just use a variable - Javascript could not alter the PHP/server-side value anyways, so it's effectively a constant.

Categories