Basically by clicking the "comment" link the last result of the query should show and by clicking again it should be hidden. I have tried Rocket's code as well but I get an error message in the bottom of the browser and when I click "comments" it just takes me to the top of the page. I would apprieciate some advice on this
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
This is a loop, echoing the same thing over and over, thus making all the divs have the same ID, something2.
IDs need to be unique, you gonna have to make unique IDs for each div.
Something like: <div id='something$i' style='display: none;'> (remembering to increment $i).
Also, you're gonna to escape the quotes in your onclick attribute.
<a href='#' onclick=\"toggle_visibility('something$i');\">
The code should look something like this:
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
Escape the quotes :
$blah = "onclick='toggle_visibility(\"something2\");'>Comments</a>"
There is an easier way to hiding / showing the next sibling ....
try this
<div style="display:none">some hidden content</div>
function toggle(el,ev) {
ev.preventDefault(); // prevent the link from being followed
el = next(el); // get the next element
if (el.style.display == "none") { // toggle the display
el.style.display = "block";
} else {
el.style.display = "none";
}
}
/*
Credit to John Resig for this function
taken from Pro JavaScript techniques
*/
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
Working example
You can throw in a counter into your code as the while loop is executing to dynamically generate unique id's for each comment div. Or, you can pull a unique field out of the query result for the id's, as long as you hook up to it appropriately later if it ends up being used and remain consistent in the rest of the code.
either
$count = count($result);
...
while (...){
$count--;
echo '... id="something'. $count .'" ...'
}
or...
while (...){
echo '... id="something'. $row['ID'] .'" ...'
}
Related
I want to make the copy button copy the value of user, but the problem is the button copied only the value of first user. When move to second user, it remain copied the valued of the first user. Here are my code.
<?php
require_once('connection.php');
$sql = "SELECT ftname, menu, longlan FROM
ownerinfo";
$result = $con->query($sql);
if ($result) {
// output data of each row
while($row = $result->fetch_assoc()) {
$a=1;
$long[$a]=$row["longlan"];
echo "Food Truck: " . $row["ftname"]. "
<br>Menu: " . $row["menu"]. "
<br>Longitude Latitude: <input id='he '
value='".$long[$a]."'></input><button
onclick='myFunction()'>Copy</button><br>
<a
href='https://maps.google.com/'>Maps</a>
<hr>";
$a=$a+1;
}
} else {
echo "0 results";
}
?>
<script>
function myFunction() {
var copyText = document.getElementById("he");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
Considering your loop outputs an ID, your JavaScript will only ever be able to target the first instance of that ID (as multiple IDs are considered invalid markup).
To correct this, output classes from your PHP instead:
<input class='he' value='".$long[$a]."'>
And loop over each of the classes in your JavaScript:
const copyText = document.getElementsByClassName("he");
for (let i = 0; i < copyText.length; i++) {
copyText[i].select();
document.execCommand("copy");
alert("Copied the text: " + copyText[i].value);
}
EDITED: with new code after help from Sgt AJ.
Ok, so I am learning all the time, but since my coder stopped coding for our website, I am now having to learn PHP fully myself.
And I see all the time the coding where my coder made function calls inside other function calls.
So first of all the setup, we have a file for pretty much 95% of all functions in our site. That functions file basically has about 40-50 functions in it.
So I'm asking if someone can explain to me how is this possible to call a function inside another which works in the below instance, but when I try replicate it, it doesn't work? displays no data when I try to echo out the $user_info?
Like for example this function below: So Sgt AJ helped me solve the user avatar issue, so that will be removed from this question!
function showComments($v)
{
$mysqli = db_connect();
$v = mysqli_real_escape_string($mysqli,$v);
$sql = "SELECT * FROM `cl45-tbn_dir`.`comments` WHERE `v` = ? ORDER BY `id` ASC";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$v);
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
if ($myrow['post_approved']==1){
$user_info = getUserInfo($myrow['poster_id']);
if ($user_info['user_avatar_type']==1) {
$avatar = "https://www.tubenations.com/forum/download/file.php?avatar=".$user_info['user_avatar'];
} else {
$avatar = "https://www.tubenations.com/forum/styles/Flato%20-%20LightBlue%20-%20Main%20Style/theme/images/no_avatar.gif";
}
echo '<div class="comment">
<div class="avatar">
<a href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">
<img src="'.$avatar.'" />
</div>
<div class="name"><a class ="myaccount'.$user_info['group_id'].'" href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">'.$user_info['username'].'</a></div>
<div class="date" title="report this post">'.date("d M Y",$myrow['post_time']).'<form action="" class="flag" method="post"><button type="submit" value="'.$myrow['id'].'" name="vote" id="votebutton" alt="vote"><img src="/images/flag.png" alt="report this post!" /></button></form></div>
<p>'.stripslashesFull(clean($myrow['post_text'])).'</p>
</div>';
}
}
$stmt->close();
$mysqli->close();
}
As you can see, there is a line where it calls another function getUserInfo, $user_info = getUserInfo($myrow['poster_id']); that is another function inside this file, and that basically connects to our forum database and gets data.
But when I try to replicate this method by using this type of call within another, it doesn't work.
So basically what I was trying to play with was trying to make a function for displaying X users data with this below function
function getYouTubeInfo($page)
{
#$id = $_GET['id'];
print_r ($userdata['user_id']);
echo $myrow['user_id'];
echo $userdata['user_id'];
$db_link = mysqli_connect ('localhost', 'HIDDEN', 'HIDDEN', 'HIDDEN');
if ( !$db_link )
{
die('following error occured: '.mysqli_error());
}
$query = "SELECT user_id, yt_channelTitle, channel_id FROM points WHERE channel_id IS NOT NULL AND yt_channelTitle IS NOT NULL ORDER BY channel_id DESC;";
if($result = mysqli_query($db_link, $query)){
echo "";
$i = -1;
$objectsPerPage = 14;
$show_records = FALSE;
while ($row = $result->fetch_assoc())
{
if (!isset($_SESSION['last_slide'])) { $_SESSION['last_slide'] = $row['channel_id']; }
if ($row['channel_id'] == $_SESSION['last_slide']) { $show_records = TRUE; }
if ($show_records)
{
$i = $i+1;
if ($i > $objectsPerPage) { $_SESSION['last_slide'] = $row['channel_id']; echo 'BREAK: ', $row['channel_id']; break; }
$page = abs(floor($i/$objectsPerPage));
$youtube_info = $row;
$userdata = getUserInfo($row['user_id']);
if ($userdata['user_avatar_type']==1) {
$avatar = "/forum/download/file.php?avatar=".$userdata['user_avatar'];
} else {
$avatar = "/images/no_image.png";
}
if (($i/$objectsPerPage)==$page)
{
if ($page !=0) {
echo "</div></div>";
}
echo '<div class="cslide-slide">
<div class="slideTitles">Youtube Users Slide '.$page.'</div>
<div class="sections grouped">';
}
echo '
<div class="cols span_1_of_2">
<div class="memberTitles">'.$youtube_info['yt_channelTitle'].''.$i.';</div>
<div class="memberPicture"><img src="'.$avatar.'" title="Tube Nations Profile Picture" alt="Tube Nations Profile Picture"/></div>
<div class="memberTwitter"><div class="g-ytsubscribe" data-channelid="'.$youtube_info['channel_id'].'" data-layout="full" data-count="default" data-onytevent="onYtEvent"></div></div>
</div> ';
}
}
echo '</div></div>';
}
mysqli_free_result($result);
echo $_SESSION['last_slide'];
session_destroy();
mysqli_close($db_link);
}
So basically in the page in question, youtube.php, I just echo this getYouTubeInfo function.
This function I need to try get the users profile pictures that are in the forum database which is from the getUserInfo($id).
Also on a side note, I also can not work out how to re arrange the $i and $objectsPerPage variables and if statements so I can then use the $page inside the query LIMIT $page; because at the moment the page crashes with no limit, so I have had to put limit to 16 for now.
I use a jQuery slide script for displaying X per slide, so if I can just somehow work out how to make the query further down after the variables and if statements for the page stuff or get any help, I would appreciate it.
EDIT UPDATED REPLY: So now the problem is it now displays X per slide/page, but it now displays a gap after 8 results are displayed when it shows 10, but with a gap, and then on the the next slide button isn't showing up? so Sgt AJ said we need to somehow connect it to the jquery?, so I now will add a tag for jquery. (But can i say a big thanks to Sgt AJ for his help, really appreciate it) :)
Wow, you've got several things going on here.
First, your query right now says LIMIT 0;, which means you should get zero rows returned. Are you getting data back from this query??
Second, to get the page and items per page working right, you could go with something like this:
In your loop, keep your i=i+1 line
Add this if:
if ($i == $objectsPerPage)
{
++$page;
i = 1;
}
This will increment the page counter once the page is full, then reset the item count for the next page.
I just wanted to add more to my question, I think now the answer is with AJAX, so I think I need to somehow make the cslide jquery code recall the getYoutubeInfo($page) function
the jquery code for the cslide is this:
(function($) {
$.fn.cslide = function() {
this.each(function() {
var slidesContainerId = "#"+($(this).attr("id"));
var len = $(slidesContainerId+" .cslide-slide").size(); // get number of slides
var slidesContainerWidth = len*100+"%"; // get width of the slide container
var slideWidth = (100/len)+"%"; // get width of the slides
// set slide container width
$(slidesContainerId+" .cslide-slides-container").css({
width : slidesContainerWidth,
visibility : "visible"
});
// set slide width
$(".cslide-slide").css({
width : slideWidth
});
// add correct classes to first and last slide
$(slidesContainerId+" .cslide-slides-container .cslide-slide").last().addClass("cslide-last");
$(slidesContainerId+" .cslide-slides-container .cslide-slide").first().addClass("cslide-first cslide-active");
// initially disable the previous arrow cuz we start on the first slide
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
// if first slide is last slide, hide the prev-next navigation
if (!$(slidesContainerId+" .cslide-slide.cslide-active.cslide-first").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-prev-next").css({
display : "block"
});
}
// handle the next clicking functionality
$(slidesContainerId+" .cslide-next").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i+1;
var slideLeft = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").next(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideLeft
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-next").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) && $(".cslide-prev").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-prev").removeClass("cslide-disabled");
}
});
// handle the prev clicking functionality
$(slidesContainerId+" .cslide-prev").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i-1;
var slideRight = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").prev(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideRight
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) && $(".cslide-next").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-next").removeClass("cslide-disabled");
}
});
});
// return this for chainability
return this;
}
}(jQuery));
I also tweaked the code that Sgt AJ helped me with again, By adding a session_destroy() just before the closing brace. And also a few other bits, because I noticed that when you refreshed the page over and over, it just loaded the next 14 results, instead of the same first 14 results, so the actual code and logic seems to be working. so it is basically now down to we need to find a way to use AJAX and recall the function from the onclick event of the next/previous buttons.
I have a new question about a project I had been working on. I was designing a grid with different colored cells. it has a hidden div which shows when a cell is clicked, however I realized that only one cell(the last one of it's type) will show. i.e. if I have 2 objects with the column "objaffinity" as 0 ("enemy") it will show both red cells on the grid, however only the last one will actually work.
how can I make it so that it will show the proper information for each cell?
here's my code:
mapgen.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="cellinfo.js"></script>
<script src="cmenu.js"></script>
<?php
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
//$xobj = array();
//$yobj = array();
$otype = array();
$oname = array();
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
$otype[$row['id']]=$row['objaffinity'];
$oname[$row['id']]=$row['object'];
}
// get the rows
$cellid=1;
//find whether the row is obstructed
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo "<td>";
//Detect what type of object it is
if (isset($xyobj[$x][$y])) {
if($otype[$cellid] == 2)
{
echo "<a href='#'> <div class='foe'> </div><div class='foepopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
elseif($otype[$cellid] == 1)
{
echo "<a href='#'><div class='friend'></div><div class='friendpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
else
{
echo "<a href='#'> <div class='neutral'></div><div class='neutralpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
$cellid++;
}
echo '</td>';
}
echo '</tr>';
}
?>
Cellinfo.js:
$(document).ready(function(){
//initially hide all popups
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").hide();
//foebutton selected
$(".foe").on("click",function(e){
$(".friendpopup").hide();
$(".neutralpopup").hide();
$(".foepopup").show();
});
//close foe when selected
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
//neutral button pressed
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
//close neutral
$(".neutralpopup").on("click",function(e){
$(".neutralpopup").hide();
});
//friend button pressed
$(".friend").on("click",function(e){
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").show();
});
//close friend
$(".friendpopup").on("click",function(e){
$(".friendpopup").hide();
});
});
In your functions you use selectors, so for the script it does not matter which div was clicked.
Let me show you some examples:
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
It should be something like this rather:
$(".foepopup").on("click",function(e){
$(this).hide();
});
And another example:
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
Rewrite it like this:
$(".neutral").on("click",function(e){
var td_tag = $(this).parent().parent();
td_tag.children(".foepopup").hide();
td_tag.children(".friendpopup").hide();
td_tag.children(".neutralpopup").show();
});
Rewrite other code on your own. this is the element on which click was triggered. td_tag will contain parent cell of a div clicked. After that, children method will allow you to find needed elements already inside specific cell.
Good luck!
I'm creating web page that fetch values from database, there are several values will be display. On each value, it will have textarea and button Tweet below. I want when user click on button tweet, it will catch the value from textarea above that button. For now, it will catch only the value from the first textarea when user click on button Tweet (all buttons).
Here is my code
PHP
while($row=mysql_fetch_array($sql)){
echo "<textarea style='margin-bottom:10px;' id='text_tweet' name='text_tweet'
cols='61' rows='5'></textarea>";
echo "<a style='text-decoration: none; color: #000000;' id='tweet'
href='#'>Tweet</a>";
}
Javascript
$("#tweet").bind('click', function(){
var text_tweet = $("#text_tweet").val();
if(text_tweet==""){
alert("Please fill out something");
}
else{
save_tweet(text_tweet);
}
});
Can anyone help me to solve this problem?
Thank in advance.
You need to distinguish between each row that is being looped out. Here's an alternate approach assuming that $row has an id.
PHP
while ($row = mysql_fetch_array($sql)) {
echo "<textarea style='margin-bottom:10px;' id='text_tweet_" . $row['id'] . "' name='text_tweet_" . $row['id'] . "' cols='61' rows='5'></textarea>";
echo "<a onclick='doSomething(" . $row['id'] . ")' style='text-decoration: none; color: #000000;' id='tweet_" . $row['id'] . "' href='#'>Tweet</a>";
}
JS
function doSomething(id) {
var text_tweet = $("#text_tweet_" + id).val();
if (text_tweet == "") {
alert("Please fill out something");
} else {
save_tweet(text_tweet);
}
}
First off, if you're going to try and grab more than one element on a page, you can't use id as that's reserved for single elements - you should never have more than one element with the same id
First, I would change it so that each element has a class called 'tweet' on it. You will also need to add the jQuery $(function(){}) around it. That function tells the browser not to run that JavaScript until the page and all elements have completely loaded.
I would also make sure to add a container around both the elements, this will make it easier for you to actually grab the textarea that is beside the the link.
Here's how I would handle it:
while($row=mysql_fetch_array($sql)){
echo "<div>";
echo "<textarea style='margin-bottom:10px;' id='text_tweet' name='text_tweet'
cols='61' rows='5'></textarea>";
echo "<a style='text-decoration: none; color: #000000;' class='tweet'
href='#'>Tweet</a>";
echo "</div>";
}
And then the javascript:
$(function() {
$(".tweet").bind('click', function(){
var text_tweet = $(this).parents('div:first').find("textarea").val();
if(text_tweet==""){
alert("Please fill out something");
}
else{
save_tweet(text_tweet);
}
});
});
The reason we do $(this).parents('div:first').find("textarea").val() is because we want to grab the textarea within that containing div only; otherwise, jQuery will grab the first textarea value in the array.
I have this script that displays all the users images which i will display below.
My question: Is there a way I can display the first 10 images in the MySQL database and have the script hide the rest of the users images until the user clicks the link View All and have the rest of the images slide down when the user clicks the link?
Here is my PHP & MySQL script?
$multiple = FALSE;
$row_count = 0;
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
if(($row_count % 5) == 0){
echo '<ul>';
}
echo '<li><img src="/images/thumbs/' . $row['url'] . '" /></li>';
if(($row_count % 5) == 4) {
$multiple = TRUE;
echo "</ul>";
} else {
$multiple = FALSE;
}
$row_count++;
}
if($multiple == FALSE) {
echo "</ul>";
}
}
echo 'View All';
Split the images into two parts. And set the second part to be hidden. Then add a click handler to slideDown. Here is the code:
UPDATE: it's not necessary to put the first 10 images into a div, but won't hurt either.
PHP
<?php
//echo '<div id="images">'; // visible images
while($row = mysqli_fetch_array($dbc)) {
// other stuff
// ...
// after the 10th image (0-9)
// open the hidden div
if ($i == 9) {
//echo '</div>'; // end of visible images
echo '<div id="hidden">'; // hidden images
}
}
echo '</div>'; // end of hidden
echo 'view all'; // view all
?>
jQuery
$(document).ready(function(){
$("#hidden").hide();
$("#view_all").click(function(){
$("#hidden").slideDown();
});
});
See it in action
Note: be sure not to hide the div with CSS. You do it in jQuery, and by this you allow users with JS disabled to get the content.
I'm not sure how many, or how large these images are, but if you want to make this scalable, I'd suggest doing an ajax callback that retrieves and fills in the "hidden" images, if the user requests them.
Yes, in your loop echoing out the list items, add the style="display:hidden" class="hidden" attribute when the count is > 10. Then use the window's scroll event to detect when the browser is scrolled near to the bottom of the window and then use jQuery to show the first hidden list item.
EDIT: This actually will show the items as the user scrolls down and does not need a "Show all button".
JQuery:
$(".hidden").hide();
$(window).scroll(function(){
if ($(window).scrollTop()+$(window).height > $("li:hidden:first").offset().top - SOMEPADDING )) {
$("li:hidden:first").fadeIn(200);
}
}