Output database row in JavaScript loop - javascript

I want to make a slideshow of data from database. I use php to print out the rows, then I placed that in a html code, then I want to use javascript to loop the code using the setInterval() loop.
My question is: how can I output the rows and use javascript to display that? because what I tried to do didn't work. I'm not experienced with javascript, and I tried to look up and try out different methods but it doesn't work for some reason.
This is what I tried to do last, but it does not print anything on page.
...
$sel_query = "SELECT * FROM `classifieds` WHERE `title` !=''";
$results = mysqli_set_charset($conn,"utf8");
$results = mysqli_query($conn,$sel_query);
while ($row = mysqli_fetch_array($results)) {
?>
...
<body>
<div id="div"> </div>
<script type="text/javascript">
setInterval(displayCode, 1000);
var codeBlock = '<div id="slider-frame" class="slider-frame">' +
'<div class="slide-images">' +
'<div class="img-container">' +
'<h1>' + '<?php echo $row['title']; ?>' + '</h1>' +
'</div>' +
'<p>' + '<?php echo $row['description']; ?>' + '</p>' +
'</div> </div>';
function displayCode() {
document.getElementById("div").innerHTML += codeBlock;
}
</script>
<?php } ?>
</body>
</html>

My problem was that the in my javascript code, did not work. It did not echo the row I wanted. I figured that this was happening because of the + in the var codeBlock. After deleting them and making the var one string it worked.
<script type="text/javascript">
setInterval(displayCode, 1000);
function displayCode() {
document.getElementById("sliderFrame").innerHTML += '<div id="sliderFrame" class="slider-frame"> <div class="slide-images"> <div class="img-container"> <h1> <?php echo $row['title']; ?> </h1> </div> <p> <?php echo $row['description']; ?> </p> </div> </div> ';
}
</script>

Related

PHP Looped Array, jquery to print each id value

So far I have managed that when a button is clicked it will print all values within the array. I need it to be smarter and only print the value of the element clicked.
<?php
$Arr_shoppingList = array(
array("Volvo",22,18,0),
array("BMW",15,13,1),
array("Saab",5,2,2),
array("Land Rover",17,15,3)
);
//Looped through array and printed values
foreach ($Arr_shoppingList as $value) {
echo "<div class='ColumnRow Spacing Color2 Border'>";
echo "<h1> $value[0] </h1> <br>";
echo "<p>'MPG'. $value[1]</p> <br>";
echo "<p>'Stock' . $value[2]</p> <br>";
echo "<form method='GET'>";
echo "<button class='Border' type='submit' id='$value[0]' class='Button'> $value[0]
</button>";
echo "</form>";
echo "</div>";
}
?>
<script>
$('button').on('click', function (event) {
event.preventDefault()
$('button').each(function(index, value){
console.log(value.id)
})
});
</script>
EDIT: The first section has been completed many thanks, but similarly, but I also need the stock and MPG values to also be targeted, how would I go about incorporating that into this code? this is part of a checkout basket I'm attempting to create.
You can use event.target.id to get the id of the clicked element
<?php
$Arr_shoppingList = array(
array("Volvo",22,18,0),
array("BMW",15,13,1),
array("Saab",5,2,2),
array("Land Rover",17,15,3)
);
//Looped through array and printed values
foreach ($Arr_shoppingList as $value) {
echo "<div class='ColumnRow Spacing Color2 Border'>";
echo "<h1> $value[0] </h1> <br>";
echo "<p>'MPG'. $value[1]</p> <br>";
echo "<p>'Stock' . $value[2]</p> <br>";
echo "<form method='GET'>";
echo "<button class='Border' type='submit' id='$value[0]' class='Button'> $value[0]
</button>";
echo "</form>";
echo "</div>";
}
?>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$('button').on('click', function (event) {
event.preventDefault()
console.log(event.target.id);
});
</script>

Link not opening in DIV using Jquery

I'm trying to use jquery to click a link in one div and have it open an HTML document in another div (named infoblock) that sits beside the original div. I found an example here but I can't get it to work. I found a couple other variations on the net, but still no luck. Part of the link needs to transmit a variable so I'm not sure if that's part of the problem. I tried attaching the click function to a div surrounding the link with an ID of "nav" as well as the link itself with an ID of "details". When I click on the link, it opens the correct page in the full window, not in the div it's supposed to go to. Thank you in advance for any help.
$(document).ready(function() {
$("#reservename").click(function() {
$("#infoblock").load("createhandle.html");
});
$("#uploadpic").click(function() {
$("#infoblock").load("uploadpic.php");
});
$("#deletechar").click(function() {
$("#infoblock").load("selectdelete.php");
});
$("#nav").click(function() {
$("#infoblock").load($(this).find("a").attr("href"));
return false;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="charlist" class="block">
<b>Your Characters:<b>
<br>
<button id="reservename">Reserve A Name</button>
<button id="uploadpic">Upload A Picture</button>
<button id="deletechar">Delete</button>
<?php
$result5 = mysqli_query($con,"SELECT * FROM handle WHERE user='$handle' ORDER BY charname ASC");
while($row = mysqli_fetch_array($result5))
{
echo "<table>";
echo "<tr>";
echo "<td rowspan=5 align=left><img src='../pictures/" . $row['face'] . "' border=3></td>";
echo "<th align=left><a href='chat.php?charname=" . $row['charname'] . "'>" . $row['charname'] . "</a></th>";
echo "</tr>";
echo "<tr>";
echo "<th align=left><a href='choosepic.php?charname=" . $row['charname'] . "'>Choose Picture</a></th>";
echo "</tr>";
echo "<tr>";
echo "<th align=left><div id='nav'><a id='details' href='../details.html?charname=" . $row['charname'] . "'>Details</a></div></th>";
echo "</tr>";
if ($row['type'] == 'new'){
echo "<tr>";
echo "<th align=left><a href='createsheet.php?charname=" . $row['charname'] . "'>Create</a></th>";
echo "</tr>";
}
echo "<hr>";
echo "</table>";
}
?>
</div>
<p id="infoblock" class="block"></p>
You have to prevent the default behaviour when anchor tag is clicked In order to do that that you have to be listen for click on the anchor itself not div and return false in order to prevent its default behaviour. So your code will become like this
$('#details').click(function(e){
{
e.preventDefault(); //instead of this you can also return false
$("#infoblock").load($('#details').attr("href"));
}
});
This works for me:
$(document).ready(function(){
$('#details').click(function(e){
e.preventDefault();
$("#infoblock").html('<object type="text/html" data="'+$('#details').attr("href")+'" >');
});
});

While loop gets killed when refreshing div

I have this JavaScript code refreshing my watcher.php file every 5 seconds and that works great. The first page load is fine but after the 5 seconds and so on the while loop gets killed. Any reason?
index.php file
<script type="text/javascript">
var auto_refresh = setInterval(function(){
$('.view').load('watcher.php');
}, 5000); // refresh div time
</script>
<body>
<div class="view">
<?php include 'watcher.php'; ?>
</div>
</body>
...
watcher.php file
include 'config.php';
$sql = "SELECT id, name, available, will_return, status FROM check_in_out";
$result = $conn->query($sql);
echo '<div style="margin-top:35px;"><center>';
echo '<table class="pure-table">
<thead>
<tr>
<th>Name</th>
<th>Available</th>
<th>Status/Comments</th>
<th>I\'ll Return At:</th>
<th>Returned</th>
</thead>
</tr>
';
if ($result->num_rows > 0) {
$i = 1;
// output data of each row
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td><img style="vertical-align:middle" src="imgs/card.jpg"> <a class="various" href="#'.$i.'"/>'.$row["name"];'</a></td>';
echo "<td>";
if ($row['available'] == 1) {
echo "<img src='imgs/available.gif'/>";
echo "Online";
} else {
echo "<img src='imgs/not-available.gif'/>";
echo "<span style='vertical-align:middle'>Away</span>";
};
echo "</td>";
echo '<td>'.$row["status"];'</td>';
echo '<td>'.$row["will_return"];'</td>';
echo '<td></td>';
echo '</tr>';
echo '<div align="center" id="'.$i++.'" style="display:none;width:520px;">
<h2>'.$row["name"].'</h2>
<!-- <h4>Current Status: '.$row["status"].'</h4> -->
<form method="post" action="statusChange.php" />
<input type="hidden" value="'.$row["id"].'" name="id"/>
<textarea rows="4" cols="50" placeholder="Enter Comment/Status Here..." name="comment"></textarea>
<br/><br/>
When will you return? - <input type="time" name="e_time">
<br/><br/>
<input class="pure-button pure-button-primary" type="submit" value="Leave/Return">
</form>
</div>';
}
} else {
echo "0 employees";
}
echo '</tr></table>';
echo '</div></center>';
$conn->close();
UPDATE:
What is by this is that look at image below. You will notice that after the first load (5 seconds) the clickable (href) gets killed...
<script type="text/javascript">
var updateWatcher = function() {
$.ajax({
url: 'watcher.php',
success: function(response) {
$('.view').html(response);
window.setTimeout(function(){
updateWatcher();
}, 3500);
}
});
}
updateWatcher();
</script>
Granted, this could be solved more elegantly with something like promises, but as far as a simple fix you could try something like this where the timer is only setup once the response has been successfully received. This should be more reliable.
Here is a simple fiddle: http://jsfiddle.net/agentfitz/26mahomm/3/ (look in the console).

How to set javascript to hide div by default in a while loop

i have a JavaScript to toggle show/hide a div class. The content of the div and the button to activate the toggle function is in a while loop. at first i used "div id" in my JavaScript but that didn't work, i decided to use "div class" instead which worked just fine. However I've not been successful in hiding the div by default, I've tried using display:none and visibility:hidden in my CSS, but that doesn't work at all (content is always hidden). How can i make the div hidden by default using my current JavaScript below:
JavaScript
<script language="JavaScript">
$(document).ready(function(){
$(".Comment").click(function(){
$(this).next(".reply").slideToggle("slow");
});
});
</script>
file.php
<?php
.......................
while($obj = $stmt->fetch())
{
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post">';
echo '<span style="font-weight:bold;">'.$username.'&nbsp&nbspsaid...
</span>';
echo '<p>'.$comment.'</p>';
echo ' <div class="Comment"><input type="button"value="Reply" ></div>';
echo '<div class="reply">';
echo '<form action="" method="post" class="reply"
enctype="multipart/form- data">';
echo '<textarea rows="4" name="txtcomment" style="float:right;resize:
none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
?>
This should work. Here is the FIDDLE
<div class="comment">Show/Hide reply.</div>
<div class="reply">A reply from someone.</div>
<script language="JavaScript">
$(document).ready(function(){
$(".reply").hide();
$(".comment").click(function(){
$(this).next(".reply").slideToggle("slow");
});
});
</script>
Things you should be aware of:
Javascript is case-sensitive, so make sure that C is correct in Comment class and the same in the document and the javascript.
You cannot hide in the CSS, you have to hide it in a style like below, otherwise the CSS overrides the javascript. You can thou change the class to hide if you want to do it that way.
<div class="reply" style="display:none;">A reply from someone.</div>
I think I covered it all now.

How do I get button's ID from a list of buttons?

I haven't worked much with php and javascript and was hoping to get some help. I want to be able to detect which button was clicked exactly. I'm creating one button per row but I don't know how to figure out what row the click was made in. This is what I have so far...
# Get all the table data from the database
$getData = mysqli_query($conn, "SELECT * FROM `query_table`") or die ("Error occured while selecting!");
// echo '<form method="post" action="index.php">';
echo '<table border="1">';
echo '<tr>';
echo '<td>Questions</td>';
echo '<td>Likes</td>';
echo '<td></td>';
echo '</tr>';
# Loop through each row and print out the question
while ($row = mysqli_fetch_array($getData)) {
echo '<tr>';
echo '<td>';
echo $row['Question'];
echo '</td>';
echo '<td>';
echo $row['Likes'];
echo '</td>';
echo '<td>';
?>
<input type="button" id="myButton" value="Like" onclick="myFunc(<?=$row['ID']?>)" />
<?php
echo '</td>';
echo '</tr>';
}
echo '</table>';
// echo '</form>';
echo '<p id="text"></p>';
mysqli_close($conn);
?>
<script type="text/javascript">
function myFunc(id) {
document.getElementById("text").innerHTML = id;
}
</script>
So far this prints out the row id where the button was clicked, but I don't suppose I can assign that parameter value directly to a php variable that I can then use for mysql queries. How is stuff like this normally done, please help.
<input type="button" data-id="<?=$row['ID']?>" value="Like" onclick="myFunc(this)">
and
<script type="text/javascript">
function myFunc(button) {
document.getElementById("text").innerHTML = button.getAttribute('data-id');
}
</script>
In JavaScript the token "this" refers to the context in which the code is running which in this case is the button. Store custom data in attributes prefixed with data- to ensure they are not disturbed - standard practise.

Categories

Resources