Php Javascript Youtube API error - javascript

I've got this code, which add videos (and videos infos) of a YouTube channel ($_POST) on a div of the Html code :
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();
//Get Video info with channel name $stringresult
$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();
$videoId = $v->getVideoId();
$thumb = $thumbs[0]['url'];
$videoViewCount = $v->getVideoViewCount();
$videoTitle = $v->getVideoTitle();
echo "newcontent.innerHTML =
'<div class=\"videos\">' +
' <div class=\"img_videos\">' +
' <img class=\"img_video\" width=\"250\" idvideo=\"".$videoId."\" ' +
' src=\"".$thumb."\"/>' +
' </div>' +
' <h3>$videoTitle</h3>' +
' <p>$videoViewCount views</p>' +
'</div>' ;";
echo "mydiv.appendChild(newcontent.firstChild);";
endforeach;
?>
The problem is, when I want to do that, it works perfectly with some channels, whereas an error has existed for others (Uncaught SyntaxError: Unexpected identifier). After several tests, I saw that by removing the display of $ videoTitle, every channels test worked. What is wrong with my code? O.o

$videoTitle seems to contains a simple quote in somes cases, which break your JS code.
Try escaping this quotes with something like this :
str_replace("'", "‚", $videoTitle)

Related

How to get the title tag to display after dynamically changing it

I am changing the title tag of a span to display the first line of the discrepancy message that it links to. Everything is working great except that the message displays onmousover, so the "magic" only happens when the user mouses over the span tag. The problem is that the title only displays if you move the mouse again, after the initial mouseover that triggers the event. Is there a way around this? Is it possible to set the title to call the JavaScript function instead of calling it on mouseover?
echo '<td valign="top" align="center">'.(($job['numberOfUnreadMessages'] > 0) ? ' <span class="badge1" id="' . $job['id'] . '" data-badge="'.$job['numberOfUnreadMessages'].'" onmouseover="showMessage(' . $job['id'] . ', ' . $job['numberOfUnreadMessages'] . ');"></div>' : ' ' );
Here is the JavaScript:
function showMessage(jobid, numOfUnreadMessages) {
let request = new XMLHttpRequest();
let jid = jobid;
request.open('GET', '<?php echo site_url('job/getDiscrepancyByJobId'); ?>/' + jobid, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
if ((this.response).contains('<div')) {
document.getElementById(jid).title = numOfUnreadMessages + ' number of unresolved discrepancies.';
} else {
let message = decodeURIComponent(this.response);
document.getElementById(jid).title = message;
document.getElementById(jid).focus();
}
} else {
// Error
}
};
request.send();
}
Thanks to O4FS for the help.
I added a field to the array being pulled into the page that brings in the discrepancy message. I then simply changed the PHP code to:
echo '<td valign="top" align="center">'.(($job['numberOfUnreadMessages'] > 0) ? ' <span class="badge1" id="' . $job['id'] . '" data-badge="'.$job['numberOfUnreadMessages'].'" title="' . $job['titleMessage'] . '"></div>' : ' ' );

How to properly concatenate values coming from Javascript and PHP?

I have been struggling with this for the last two hours and I can't get it to work. Take a look to the following piece of code:
$js = '$.extend($.fn.fmatter , {
userActions : function(cellvalue, options, rowData, addOrEdit) {
var data = cellvalue.split("|");
var id = options.rowId;
var actions = "";';
foreach ($editorActions as $linkType => $value) {
switch ($linkType) {
case 'view':
$js .= "if(data[1] == 1) {
actions += \"<a class='actionimage' href='" . $value . " + options.rowId' title='" . $this->translate->_e('View') . "' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>\";
}";
}
break;
}
As you can see id is a value coming from Javascript and $value is coming from PHP. The idea is to get an hyperlink as for example:
$value = "/route/to/function/";
id = 19009; // I've omitted the $ sign since this var is coming from JS
var href = "' . $value . '" + id;'
Then I need to use the href var as part of the <a> element shown right after the definition.
With my code above I am getting this error:
Uncaught SyntaxError: Invalid or unexpected token
Can I get some help to get this right?
UPDATE:
This is how the code looks like after I render the page:
$(function () {
$.extend($.fn.fmatter, {
userActions: function (cellvalue, options, rowdata) {
var data = cellvalue.split('|');
var id = options.rowId;
var actions = '';
console.log(id);
if (data[1] == 1) {
actions += "<a class='actionimage' href='/sf/distributor/show/ + options.rowId' title='View' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>";
}
return actions;
}
});
});
Notice how the function $.extend close properly. console.log(id) did print the value of options.rowId however this value doesn't have any effect on the hyperlink as you may notice this is the value /sf/distributor/show/ + options.rowId.
What is coming in $value is a plain string in the case above /sf/distributor/show/.
You're missing double quotes and to end and reopen the string around options.rowId and a + in:
actions += \"<a class='actionimage' href='" . $value . " + options.rowId'
It should be:
actions += \"<a class='actionimage' href='" . $value . "\" + options.rowId + \"'
Here you are missing "" and that way you are adding options.rowId as a string text.
href='/sf/distributor/show/" + options.rowId + "'

Unwanted JSON Response

I'm using this small JSON function with a database.
<script>
$(document).ready(function () {
var url = "Database.php";
$("#jsondata tbody").html("");
$.getJSON(url, function (data) {
$.each(data.users, function (i, user) {
var songdetails = "<p>"
+ "<p>" + user.Title + "</p>"
+ "<p>" + user.ArtistNumber + "</p>"
+ "<p>" + user.TrackTime + "</p>"
+ "<p>" + user.Composer + "</p>"
+ "<p>" + user.Lyricist + "</p>"
+ "</p>";
$(songdetails).appendTo("songlist");
});
});
});
</script>
This produces this in the browser, which I don't want/need.
{"users":[{"Title":"Anyway","ArtistNumber":"2","TrackTime":"167","Composer":"John
Glaze","Lyricist":"Kellee
Maize","FileLocation":"public/Anyway.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"One
Way Heartbeats","ArtistNumber":"4","TrackTime":"187","Composer":"Bill
Bobs","Lyricist":"Michael
McEachern","FileLocation":"public/OneWayHeartbeats.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Parallel
Me","ArtistNumber":"3","TrackTime":"192","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"private/ParallelMe.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"1"},{"Title":"Poisoned
Oxygen","ArtistNumber":"3","TrackTime":"177","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"public/PoisonedOxygen.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Xmas
Prison Blues","ArtistNumber":"1","TrackTime":"192","Composer":"Steve
Perry","Lyricist":"Steve
Perry","FileLocation":"private/XmasPrisonBlues.wma","rated":"0","scores":"[0,0,0,0,0]","free":"1"}]}
Any ideas on how to hide it or remove it from coming up?
Thanks
This is the Database.php:
<?php
$Hostserver = "localhost";
$databUser = "ee2800";
$databPass = "secret";
$databDatabase = "ee2800";
$database = new mysqli ($Hostserver, $databUser, $databPass, $databDatabase);
if ($database) {
mysqli_select_db($database, "ee2800");
//echo ("Successfully connected to database!");
} else {
die ("<strong>Error:</strong> Failed to connect to the database.");
}
$var = array();
$sql = "SELECT * FROM songs";
$result = mysqli_query($database, $sql);
while ($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":' . json_encode($var) . '}';
?>
Using jQuery 1.10.2
The songlist element is found here
<?php
// The system queries the database to obtain a result set containing no more than 10 artists //
if ($result = $database->query( "SELECT * FROM `artist` ORDER BY `artist`.`ArtistNumber` ASC LIMIT 10")) {
while ($row = $result->fetch_row()) {
echo "<div id='artist{$row[2]}'>";
echo "<p>Artist: {$row[0]} {$row[1]}</p>";
echo '<p><div id= songlist> </div> </p>';
//div tag 'songlist' adds all data from json and pastes into this div id //
// echo '<p>Songs</p>';
//onlick function echo'd anchor tag//
echo "</div>";
// Songs dont display onclick however retrieved data using jSON can't seem to target where to put the information //
}
}
$database->close();
?>
And basically whenever I run these files, I get that long string I stated at the beginning as a response in my browser everytime.
Well your PHP appears to be returning a valid json string, but it is not being coverted automatically to a json object so that it can be processed by javascript as an object.
You could try forcing the parse to a json object like this
$.getJSON(url, function (data) {
data = $.parseJSON(data);
$.each(data.users, function (i, user) {

php javascript drag and drop

Hey guys i got a problem with my DnD solution.
It works well as long as i dont write something into my textarea. That means if the page is loading data from MySQL into the Area it works, if i try to put write something in it by my self it doesnt.
Does someone know how i can fix this? so that i can write into my Area and still drop something in there?
Below the important part of the Script if you need more to see why it is not working, let me know.
Got the Code for it from:
http://www.dhtmlgoodies.com/index.html?whichScript=drag-drop-custom
Generating dragabele Image preview:
$dir = "../../images";
$handle=opendir ($dir);
while (($file = readdir ($handle)) !== false) {
if ( filetype( $dir.'/'.$file) == "file"
AND ((substr( $file, -4) == ".jpg")
|| (substr( $file, -4) == ".png")
|| (substr( $file, -4) == ".gif"))){
echo " <div id='".$file."' style='float: left; width:120px; height:125px; border-width:1px; border-style:solid; border-color:black;'>
<img src=".$dir."/".$file." width=110 style='height: 110px;'>
$file
</div>";
echo " <script type='text/javascript'>
dragDropObj.addSource('".$file."',true);
</script>";
}
}
closedir($handle);
Now im dropping them into a textarea with the following Javascript:
<script type="text/javascript">
function dropImg1(idOfDraggedItem,targetId,x,y){
var html = document.getElementById('text_kurz').innerHTML;
if(html.length>0)html = html + ' ';
html = html + '<img src="/images/' + idOfDraggedItem+'">';
document.getElementById('text_kurz').innerHTML = html;
}
function dropImg2(idOfDraggedItem,targetId,x,y){
var html = document.getElementById('text_lang').innerHTML;
if(html.length>0)html = html + ' ';
html = html + '<img src="/images/' + idOfDraggedItem+'">';
document.getElementById('text_lang').innerHTML = html;
}
function dropImg3(idOfDraggedItem,targetId,x,y){
var html = document.getElementById('nachwort').innerHTML;
if(html.length>0)html = html + ' ';
html = html + '<img src="/images/' + idOfDraggedItem+'">';
document.getElementById('nachwort').innerHTML = html;
}
var dragDropObj = new DHTMLgoodies_dragDrop();
</script>
OK Guys ive got the solution... its that simple that i didnt even thought about that...
its just:
.innerHTML
to
.value
Thanks anyway ;)
Hope i could help out someone having the same problem

Rewrite code from javascript to PHP

I have code in javascript:
if (imageData[imageCount].comments.data != null)
{
text = 'Comments Data:<br />';
imageData[imageCount].comments.data.forEach(function(comment){
text += comment.from.username + ': ' + comment.text + '<br />';
});
}
Which imageData[imageCount] refers to $data in PHP.
i've trying to rewrite self in PHP but it doesn't worked.
foreach ($contents->data as $data) {
if ($data->comments->data != null)
{
foreach($data->comments->data as $comment)
{
$text = comment->from->username + ': ' + comment->text + '<br />';
});
}
I'm sure to have problem with the code structure. It returns Invalid argument supplied for foreach()
-- Edit --
I've successed to convert the snippet to PHP. But i faced a new problem since i'm trying to create XML File from API (in this case Instagram API).
Look at productName and productPrice attribute from product section:
http://pastebin.com/ubGGyp9b
Value productName="Sushi Homemade " and productPrice="50.000 " is just for productID="002". But why the value also filled to next productID >= 002.
Is there mistake from this code:
<products>
<category categoryName="Instagram">
<?php
foreach ($contents->data as $data) {
foreach($data->comments->data as $comment){
if(preg_match('/#title/', $comment->text)){
$komen = preg_replace('/#title/', '', $comment->text);
break;
} else { $komen = 'No Title'; }
}
foreach($data->comments->data as $comment){
if(preg_match('/#price/', $comment->text)){
$harga = preg_replace('/#price/', '', $comment->text);
break;
} else { $harga = '0'; }
}
echo '<product productName="'. $komen .'" productID="' . $data->id . '" thumbPath="' . $data->images->thumbnail->url . '" productPrice="'. $harga .'">
<details>
<![CDATA[
<img src="' . $data->images->low_resolution->url . '" width="100%"/>
' . $data->caption->text . '
]]>
</details>
</product>
You forgot an $ in the last line and some brackets were not correctly set. To concat strings in PHP use "." instead of "+"
foreach ($contents->data as $data) {
if ($data->comments->data != null) {
foreach ($data->comments->data as $comment) {
$text = $comment->from->username . ': ' . $comment->text . '<br />';
}
}
}

Categories