I'm echoing rows and would like to either delete them or increment them like a thumbs up effect... I can't seem to identify the rows individually.
This is my included jquery source
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
There are no errors in the javascript web console...
This is the click function I'm trying to implement with a test ['clicked']:
<script type="text/javascript">
$(":button").click(function() {
var selectedId = $( this ).attr(id);
alert(selectedId);
alert('clicked');
});
</script>
These are my rows which I have echoed:
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR.'dbconnect.php');
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT COUNT(*) FROM entries";
if ($result = $link->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
if($row[0]==0){
echo "There are no entries.";
}else {
$query2 = "SELECT id,saying,date,thumbs_up,comments FROM entries ORDER by ID ASC ";
if (($result = $link->query($query2))) {
/* fetch object array */
while ($row = $result->fetch_row()) {
echo
'<div class="primary-container" align="center">'.
'<div class="entry-container" align="center">'.
$row[1]." ".
'</div>'.
'<div class="bird" align="center">'.
'Bird Up!'.
'</div>'.
'<div class="birdups" align="center">'.
$row[3].
'</div>'.
'<div class="thumbup" align="center">'.
'<button name="increment" class="button" id="'.$row[0].'">'.
'<img src="bird_up.png" width="100%" height="auto" alt="bird up thumbs up like equivalent thumbnail">'.
'</button>'.
'</div>'.
'</div>'.
'<br>'
;
}
}
}
}
/* free result set */
$result->close();
}
?>
Use event delegation for newly added html elements. And you have missed out put the single quotes for id. I hope it solves your issues thanks
$(document).on("click" , ".button" , function() {
var selectedId = $(this).attr('id');
alert(selectedId);
});
Related
I am trying to make a website but I am very new to the jquery stuff and I added jquery load more comment into my website
My question is, I have a load more button that works the way I intended it to work however when all the data are loaded or when there is no comment I can't seem to get the load button to turn hidden
//jquery script
<script>
$(document).ready(function() {
var commentCount = 20;
var qidNow = "<?php echo $qid; ?>";
$("button").click(function() {
commentCount = commentCount + 20;
$("#comments").load("includes/load-comments.inc.php", {
commentNewCount: commentCount,
qid: qidNow
});
});
});
//load-comments page
<?PHP
require 'dbh.inc.php';
include 'function.inc.php';
$commentNewCount = $_POST["commentNewCount"];
$qid = $_POST["qid"];
$count = 0;
$sqlComment = "SELECT comment, commentTime, commenterId FROM comments WHERE commentOn = ?
LIMIT ?";
$stmtComment = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmtComment, $sqlComment)) {
header("Location: ../viewtopic.php?error=sqlerror4");
exit();
} else {
//bind parameter to the placeholder
mysqli_stmt_bind_param($stmtComment, "ii", $qid, $commentNewCount);
//run parameter inside database
mysqli_stmt_execute($stmtComment);
$commentData = mysqli_stmt_get_result($stmtComment);
}
if (mysqli_num_rows($commentData) > 0) {
while ($row = mysqli_fetch_assoc($commentData)) {
$count++;
echo "<div class='individualComment'>";
echo "<div class='commentCount'> คอมเม้นที่" . $count . "</div>";
echo "<div class='actualComment'>" . $row['comment'] . "</div>";
echo "<div class='commentDateBx'>" . dateReformat($row['commentTime']) . "</div>";
echo "<div class='commenterIdBx'>ID :" . $row['commenterId'] . "</div>";
echo "</div>";
}
}else {
echo "There is no comment yet";
}
I have my triggers and divs to show/hide in a while loop, instead of using div id which has to unique, i've decided to use div class to show/hide a group of content among others.
what i'm trying to achieve:
i'm not at all good with javascript, and i've been trying to achieve this for days. Say i have a trigger with div class="view1-'.$id1.'" where $id1=2 and div class="licom-'.$cc_id.'" where $cc_id=2 to show/hide, is it possible to ensure that my trigger would only show/hide the div class with the same id as 2?.
JavaScript
<html>
<head>
<script language="JavaScript">
$(document).ready(function(){
var showText='View all replies';
var hideText='Hide';
// initialise the visibility check
var is_visible = false;
// append show/hide links
$('.view1').prev().append();
$(".licom").hide();
$(".view1").click(function(){//i need to pass the div class with the variable
// switch visibility
is_visible = !is_visible;
// change the link depending on whether the element is shown or hidden
$(this).html( (!is_visible) ? showText : hideText);
//i also need to pass the right div class with the right variable, and keep the others hidden
$('.licom').toggle(function() {
$(this).closest('view1').find('.licom').hide();
return false;
},
function() {
$(this).closest("view1").next(".licom").show();
return false;
});
});
});
</script>
</head>
<body>
</body>
</html>
info.php
<?php
...........
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
while($obj = $stmt->fetch()){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id1 = $obj['id'];
$userimage = $obj['user_image'];
echo '<div class="txt">';
echo '<div class="comment-container">';
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.'  said....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
//trigger to hide/show replies
echo '<span class="view1-'.$id1.'" style="float:right;margin-top:-15px;">View all replies</span>';
//
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
//Relpy to comment, show only the first row
$rep = $conn->prepare("SELECT * FROM reply WHERE comment_id = :comid LIMIT 1");
$rep->bindParam(":pid", $id1, PDO::PARAM_INT);
$rep->execute();
while($obj = $rep->fetch()){
//...........same output as first without the view all replies trigger......
//Relpy to comment, show from row 2-
$rep = $conn->prepare("SELECT * FROM reply WHERE comment_id = :comid LIMIT 1,18446744073709551615");
$rep->bindParam(":pid", $id1, PDO::PARAM_INT);
$rep->execute();
while($obj = $rep->fetch()){
$cc_id = $obj['comment_id'];
//div to show/hide
echo '<div class="licom-'.$cc_id.'">';
//...........same output as first without the view all replies trigger......
}
}
}
?>
how do i re-write my JavaScript so that all div of class "licom" are hidden by default, and only the div with the same id as the trigger say 2,3,... as the case maybe would show/hide onClick.
As requested in the comments on question:
"Something like: http://jsfiddle.net/qjadyznh/ ?"
$('a').click(function(){
var id = $(this).attr('id');
if($('.'+id).css('display') == 'none')
{
$('.'+id).css('display','block');
}
else
{
$('.'+id).css('display','none');
}
})
Simple example on how to achieve the goal needed.
I need Give row color after onClick row and make request other page and stay color changed
Notes: Currentaly change row color and disable color changed after refres page
<script type="text/javascript">
var id = $row['id'];
function myPopup(id) {
if (id) {
location.href = "address.php?id="+id;
}
}
</script>
<script>
$(document).ready(function () {
$('#imagetable tr').click(function () {
$(this).css('background-color', 'Green');
});
});
</script>
<?php
$resualt=mssql_query("SELECT * FROM Address ") ;
echo "<table border='1' class='imagetable'
id='imagetable' width='50%'>\n";
echo '<tr>';
echo '<th>ID</th>'.'<th>User ID</th>'.'<th>Street</th>'.'<th>Quarter</th>'.'<th>Mobile Number</th>'.'<th>Email</th>'.'<th>From</th>'.'<th>To</th>'.'<th>Notes</th>';
echo '</tr>';
while ($row = mssql_fetch_assoc($resualt)) {
echo "<tr onClick='myPopup($row[id])'>\n"."<td >{$row['id']}</td>\n"."<td> {$row['user_id']}</td>\n"."<td>{$row['street']}</td>\n"."<td>{$row['quarter']}</td>\n"."<td>{$row['Phone_number']}</td>\n"."<td> {$row['email']}</td>\n"."<td>{$row['from_date']}</td>\n"."<td>{$row['to_date']}</td>\n"."<td>{$row['other_info']}</td>\n".'</tr>'."\n";
}
echo "</table>\n";
?>
Any help?
In your PHP check if the given ID matches the ID in the while loop. When that matches, add a style parameter or a CSS class depending on your situation.
Examples:
// Your code leading up to the while loop is here ...
while ($row = mssql_fetch_assoc($resualt)) {
echo "<tr onClick='myPopup($row[id])" . ($_GET['id'] == $row[id] ? "style='background-color: green'":"") . "'>\n".
"<td >{$row['id']}</td>\n".
// The rest of the code in your loop continues here ...
It is not the most beautiful or safe code, but it suits the code you already have i think.
I have a data set of items coming from a SQL database. Those items are displayed in multiple divs like:
<?php
$url = 'DataBase';
$json_response = file_get_contents ( $url );
$json_arr = json_decode ( $json_response, true );
for($i = count ( $json_arr )-1; $i > 0; $i--) {
$json_obj = $json_arr [$i];
echo '<div id="MyDIV">';
echo $json_obj ['id'] ;
echo $json_obj ['title'];
echo $json_obj ['article'];
echo '<button id="read_more_btn">Read more</button>';
echo '</div>'
}
?>
My problem is that I cannot handle click events for EACH div, so I cannot identify which item has been clicked. I’ve been searching for a solution for quite a while, but haven’t found anything. So my question is – how can I identify the clicked item?
EDIT
I have no idea how I can dynamically assign an ID to a button
You could use a data attributes (HTML5 assumed) to attach the Id as meta data to your divs. Your PHP (note I am adding data-id attributes):
<?php
$url = 'DataBase';
$json_response = file_get_contents ( $url );
$json_arr = json_decode ( $json_response, true );
for($i = count ( $json_arr )-1; $i > 0; $i--) {
$json_obj = $json_arr [$i];
echo '<div data-id="' . $json_obj['id'] . '">';
echo $json_obj ['id'] ;
echo $json_obj ['title'];
echo $json_obj ['article'];
echo '<button id="read_more_btn">Read more</button>';
echo '</div>'
}
?>
JS - simple click handler attachment, using jQuery .data() [docs] to get data attribute:
$('div').click(function(e) {
var id = $(this).data("id");
alert(id);
});
JSFiddle Demo
How about when creating the html in the php, you echo the id inside the class.
echo '<div id="mydiv-' . $json_obj['id'] . '">';
So now in the html, it's going to look like
<div id="mydiv-1"> ... </div>
<div id="mydiv-2"> ... </div>
<div id="mydiv-3"> ... </div>
etc.
And then in Javascript, you could access them the same way you access any tag.
$('#mydiv-1').click(function(e){
console.log('a div was clicked');
console.log($(this))
});
So in order to assign listeners to each div, you could do a loop
for(var i = 1;$('#mydiv-container').children().length >= i,i++)
{
$('#mydiv-' + i).click(function(){
}
Make sure to add a container for all the divs.
Give each div a unique numeric class, so your jquery will be
$('div').click(function() {
var item_id = $(this).attr("class");
//do stuff here
});
or
$('div').click(function() {
var item_id = this.className;
//do stuff here
});
I have the following two pages. The index.php includes purchases_pending.php through PHP. The first time the page loads the form works perfectly but when the DIV(#pp) is refreshed after 10 seconds the FORM does not work. Is there a solution for this? Or if I can do it through AJAX, can somebody help me with the code. As you have seen my codes you'll probably know Im a beginner.
Thanks in advance.
index.php
<script type="text/javascript">
function update(){
$('#pp').load('/status/purchases_pending.php');
}
setInterval( update, 10000 );
</script>
<div class="content">
<div class="content_left">
<p>
<h3>Pending Purchases</h3>
<div class="user_content"><div id="pp"><?php include ($purchases_pending); ?></div></div>
</p>
purchases_pending.php
<?php
$CONFIG = $_SERVER["DOCUMENT_ROOT"]. "/config/";
include($CONFIG. "pages.php");
include($db);
$sql = "SELECT * FROM account WHERE status='Pending' AND type='Purchase'";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
echo '<table>';
echo '<tr> <th align="left">Party</th> <th>Box</th> <th>Rate</th> <th>Status</th> </tr>';
while ($result = mysqli_fetch_assoc($query)) {
$id = $result['id'];
$party = $result['party'];
$box = $result['box'];
$rate = $result['rate'];
$amount = $result['amount'];
echo '<form action="" method="post">';
echo '<tr>';
echo '<td>' . $party . '</td>';
echo '<td align="center">' . $box . '</td>';
echo '<td align="right">' . $rate . '</td>';
echo '<td align="center"><input type="checkbox" name="status[]" id="status[]" value="' . $id . '" /></td>';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="submit" value="Completed" class="input" />';
echo '</form>';
}
else {
echo 'Hooray...No pending purchases';
}
if(isset($_POST['submit']) && $_POST['submit']!="") {
$status = $_POST['status'];
$count = count($_POST['status']);
for($i=0;$i<$count;$i++) {
$update_purchases = "UPDATE account SET status='Completed', user_confirm='$user_confirm' ,user_confirm_time=current_timestamp WHERE id='$status[$i]'";
$query_purchases = mysqli_query($conn, $update_purchases);
}
header ('location:/');
}
?>
load the JS function outside the jquery
<script>
function update(){
$('#pp').load('/status/purchases_pending.php');
}
</script>
$( document ).ready(function() {
setInterval( update, 10000 );
});
JS load needs to be in document ready in order to work.
Short hand is
$(function() {
var update = function() {
$('#pp').load('/status/purchases_pending.php');
setTimeout(update, 10000);
}
update();
});
Move this code to index.php as this no longer exist in the page because it gets removed when replacing div #pp
if(isset($_POST['submit']) && $_POST['submit']!="") {
$status = $_POST['status'];
$count = count($_POST['status']);
for($i=0;$i<$count;$i++) {
$update_purchases = "UPDATE account SET status='Completed', user_confirm='$user_confirm' ,user_confirm_time=current_timestamp WHERE id='$status[$i]'";
$query_purchases = mysqli_query($conn, $update_purchases);
}
To explain php renders from the server as html, it reads top to bottom.
So when the js inserts it, it is not inserting the code, but rather the rendering of the code.
Ajax is used to send data, but on load no data is being sent other than give me a form.
The post doesn't exist because it is already rendered. When using an include it is "inserted" as part of the code to be executed and thus works.