I am trying to make a PHP page that embeds a JavaScript into the page that makes some YouTube videos on the page and so on, that works fine, but I have another script on the page that should sort these YouTube videos based on the amount of views they have. That normally works, but since I started working on PHP for the page so I don't have to hardcode everything, it doesn't work.
Code:
<script src="jquery-3.2.1.min.js"></script>
<html>
<body>
<?php
$youtubeID = array("KxEhALUc_xo", "HHuOu8L5f58", "DANypN7iXsI");
$len = count($youtubeID);
for ($i = 0; $i < $len; $i++) {
$embedCode = "<script>
var id = ('" . $youtubeID[$i] . "')
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $youtubeID[$i] . "&key=', function(data) {
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" . $youtubeID[$i] . "&key=', function(data2) {
var tags = data2.items[0].snippet.tags;
var likes = data.items[0].statistics.likeCount;
var viewcount = data.items[0].statistics.viewCount;
var title = data2.items[0].snippet.title;
var channel = data2.items[0].snippet.channelTitle;
$('div#videocontainer').append('<div class = videoframe><iframe src = \"https:\\\\\\\\www.youtube.com\\\\embed\\\\" . $youtubeID[$i] . "\" width = 854 height = 510 frameborder= 0 allowfullscreen></iframe><div class = countercontainer><div class = counter>View count:'+viewcount+'</div></div><div class = titlecontainer><div class = title>'+title+'</div></div><div class = likescontainer><div class = likes>'+likes+'</div></div></div>');
});
});
</script>
";
echo $embedCode;
}
?>
<script>
$('button#viewsasc').click(function() {
var videos = $('div.videoframe').get();
videos.sort(function(a,b) {
return parseInt($(a).find('div.counter').text()) - parseInt($(b).find('div.counter').text());
});
$('div#sortedcontainer').html($(videos));
});
$('button#viewsdesc').click(function() {
var videos = $('div.videoframe').get();
videos.sort(function(a,b) {
return parseInt($(b).find('div.counter').text()) - parseInt($(a).find('div.counter').text());
});
$('div#sortedcontainer').html($(videos));
});
</script>
<button id = 'viewsasc'>desc</button>
<button id = 'viewsdesc'>asc</button>
<div id = 'videocontainer'></div>
<div id = 'sortedcontainer'></div>
</body>
</html>
I know it all looks like a mess, but its just a prototype ;).
So as you can see, I have a little array with 3 YouTube video IDs, I then try to embed a JavaScript code that will get som JSON data, make some divs, and show the video with youtubes "iframe".
That all works good, I have 3 YouTube videos showing on my page, and I have the external text with all the views, title, and likes showned.
WHAT's not working is this part:
<script>
$('button#viewsasc').click(function() {
var videos = $('div.videoframe').get();
videos.sort(function(a,b) {
return parseInt($(a).find('div.counter').text()) - parseInt($(b).find('div.counter').text());
});
$('div#sortedcontainer').html($(videos));
});
$('button#viewsdesc').click(function() {
var videos = $('div.videoframe').get();
videos.sort(function(a,b) {
return parseInt($(b).find('div.counter').text()) - parseInt($(a).find('div.counter').text());
});
$('div#sortedcontainer').html($(videos));
});
</script>
<button id = 'viewsasc'>desc</button>
<button id = 'viewsdesc'>asc</button>
<div id = 'videocontainer'></div>
<div id = 'sortedcontainer'></div>
So when i press these buttons:
<button id = 'viewsasc'>desc</button>
<button id = 'viewsdesc'>asc</button>
it will indeed move the "videoframe" div into the "sortedcontainer" div, but it is not sorted, it's just moved to another div, so that's pretty useless. Here is gyazo so you can see what i mean: https://gyazo.com/dc9baa1f1342ffc08c66b2db41d3a4d0
I am very confused by PHP and not very good at it as you can guess, there is probably some obvious rule I didn't know about, I only just started to study PHP.
Related
I have a PHP function that loops through image results in a database, formats them with HTML, then returns the variable containing the HTML layout to my page.php. This is all working okay, but in the loop I have some script tags that call a function in my script.js file. It takes two parameters (url and count). I am trying to pass the url of the result from the database to the function, create a new img element, and append the passed url to the src attribute of the newly created img tag.
This appears to be working so far - when I console.log the result, I get a load of <img> tags, all with corresponding src attached to them.
I am having trouble with actually getting these back to the front end, though.
My code below shows the part of the php that gets looped through, followed be the Javascript function it calls on each loop.
public function getResultsHtml($page, $pageSize, $term) {
$fromLimit = ($page - 1) * $pageSize;
$query = $this->con->prepare("SELECT * FROM images
WHERE (title LIKE :term
OR alt LIKE :term) AND broken=0
ORDER BY clicks DESC
LIMIT :fromLimit, :pageSize");
$searchTerm = "%" . $term . "%";
$query->bindParam(":term", $searchTerm);
$query->bindParam(":fromLimit", $fromLimit, PDO::PARAM_INT);
$query->bindParam(":pageSize", $pageSize, PDO::PARAM_INT);
$query->execute();
$resultsHtml = "<div class='image-results'>";
$count = 0;
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$count++;
$id = $row["id"];
$imgUrl = $row["imgUrl"];
$siteUrl = $row["siteUrl"];
$title = $row["title"];
$alt = $row["alt"];
if($title){
$displayText = $title;
} else if ($alt) {
$displayText = $alt;
} else {
$displayText = $imgUrl;
}
$resultsHtml .= "<div class='grid-item image$count'>
<a href='$imgUrl'>
<script>
document.addEventListener('DOMContentLoaded', function() {
loadImage(\"$imgUrl\", \"image$count\");
});
</script>
<span class='details'>$displayText</span>
</a>
</div>";
}
$resultsHtml .= "</div>";
return $resultsHtml;
}
var loadImage = function(src, className){
var image = document.createElement("img");
var aTag = document.querySelectorAll("." + className + " a");
image.onload = function(){
aTag.innerHTML = image;
};
image.onerror = function(){
};
image.setAttribute("src", src);
}
At the moment I'm not geting any results at the front end. In the page source, I can see that inside each anchor tag are script tags, which show the function preloaded with the parameters (loadImage(http://www.com, image22)), but it isn't actually getting a return from the function.
The solution for this with jQuery is below, but I really don't want to use jQuery!
function loadImage(src, className) {
var image = $("<img>");
image.on("load", function() {
$("." + className + " a").append(image);
});
image.on("error", function() {
});
image.attr("src", src);
}
I know that there is some trouble with dynamically writing <script> tags with .innerHTML, but I don't think this is the problem as the script tags are written before the function is called.
I think I have something firing in the wrong order, or I'm missing something that jQuery handles automatically with the .append function.
I have also tried aTag.appendChild(image);, which also gives no results.
I have been using jQuery for a few months, but I am trying to learn Vanilla JS thoroughly - I'm trying to grasp how the jQuery functions actually work, rather than just relying on them blindly.
Any help is massively appreciated!
Beware of that querySelectorAll() returns an array-like NodeList (https://developer.mozilla.org/en-US/docs/Web/API/NodeList), so it should be like this:
(If you only want one element returned user querySelector(), then you don't need the loop)
function loadImage(src, className) {
var image = document.createElement("img");
image.src = src;
image.onload = function() {
var tags = document.querySelectorAll("." + className + " a");
for (var i = 0; i < tags.length; i++) {
tags[i].appendChild(image);
}
}
}
<div class='grid-item image2'>
<a href='https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg'>
<script>
document.addEventListener('DOMContentLoaded', function() { loadImage("https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg", "image2");
});
</script>
<span class='details'>Star Wars 1</span>
</a>
</div>
The problem is that you are using querySelectorAll, which returns a NodeList instead of a single DOM node. This means, you have to iterate over the NodeList and append the image to all the nodes within. For this, you have can either create new copies for each place you want to insert the image, or use cloneNode multiple times.
var each = function (xs, func) {
for (var i = 0; i < xs.length; i += 1) {
func(xs[i]);
}
return xs;
}
var loadImage = function(src, className){
var image = document.createElement("img");
var aTag = document.querySelectorAll("." + className + " a");
image.onload = function(){
each(aTag, function (a) {
a.appendChild(image.cloneNode());
});
};
image.onerror = function(){};
image.alt = '';
image.src = src;
}
loadImage('http://www.fillmurray.com/500/300', 'wrap')
<div class="wrap">
</div>
I'm trying to update multiple <div> without refreshing the whole page and figured that if I cycle through an array using the index I can achieve that, but it's not working at all.
However when I replace event[index]['fullName'] in the prevEvent function with index, the page gets updated.
How do I update the page contents without refreshing the whole page?
<script type="text/javascript" >
var index=0;
//pass php array to javascript
var event= <?php echo json_encode($event); ?>;
document.getElementById("fullName").innerHTML = event[index]['fullName'];
document.getElementById("emailAddress").innerHTML = event[index]['emailAddress'];
document.getElementById("phoneNumber").innerHTML = event[index]['phoneNumber'];
document.getElementById("childName").innerHTML = event[index]['childName'];
document.getElementById("theater").innerHTML = event[index]['theater'];
document.getElementById("movie").innerHTML = event[index]['movie'];
document.getElementById("eventDate").innerHTML = event[index]['eventDate'];
document.getElementById("eventTime").innerHTML = event[index]['eventTime'];
document.getElementById("eventType").innerHTML = event[index]['eventType'];
document.getElementById("numOfPeople").innerHTML = event[index]['numOfPeople'];
document.getElementById("partyRoomBook").innerHTML = event[index]['partyRoomBook'];
document.getElementById("partyRoomTime").innerHTML = event[index]['partyRoomTime'];
document.getElementById("description").innerHTML = event[index]['description'];
document.getElementById("specialAttention").innerHTML = event[index]['specialAttention'];
function prevEvent(){
index--;
document.getElementById("fullName").innerHTML = event[index]['fullName'];
}
</script>
I was wondering if it's possible to get a sequence of pictures into an array. I'd like to use JavaScript if possible, if not can it be possible with PHP and how?
So I created a map called "images/cars", which contains a lot of images. All the pictures have a different name. One is called: "audi", another one is called: "mercedes" and so on. They all are the same type (.gif).
I can do this manually like:
var pictures = ["audi.gif", "mercedes.gif", "aston martin.gif", ....]
// and so on
But that is too much work. Also, when I upload a new picture to the "images" folder, I have to manually add the new image to the array.
Here is my full code :
<!DOCTYPE html>
<html>
<head>
<script>
var cars= ["audi.gif", "mercedes.gif", "aston martin.gif", "bmw.gif", "ferrari.gif"];
var outputRandomImage = "";
function myFunction() {
for (var i = cars.length - 1; i >=0; i--) {
var random = Math.floor(Math.random()*(i+1));
var randomImage = cars[random];
cars[random] = cars[i];
cars[i] = randomImage;
outputRandomImage += '<img src="images/cars/' + randomImage + '">' + "<br>";
document.getElementById("output").innerHTML = outputRandomImage;
}
}
</script>
</head>
<body onload="myFunction()">
<p id="output"></p>
</body>
</html>
Hope someone here could help. I'm open to any ideas, recommendations, and suggestions. Thank you.
One way is to create another PHP page
$folder = "."; // folder with the image files
$scan = scandir($folder);
$files = [];
foreach($scan as $file_name)
{
if (!is_dir("$folder/$file_name"))
{
$array_push($files, $file_name) // if it is not a directory add it to the files list
}
}
$json_string = json_encode($ar);
echo $json_string;
And for the javascript
$.post("getCars.php", function(data, status){
if(status==="success"){
cars = JSON.parse(data)
}
});
I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>
I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>