This is my PHP code and each post has a More button with the same class. I want if I click on More button of post A, only the comments under it should be displayed :
<?php
for ($i = 1; $i <= 10; $i++) {
echo "<div class='col-md-6'>";
echo "<div class = 'feeds'>"; ?>
<form method='post' class='murconform form-horizontal' name='signinform'
action =''>
<?php
echo "<p>". $post . "</p>";
echo "<div class = 'murcons btn-group'>";
echo "<span class = 'likecount'>". $likes . "</span><button class='mlike pacedown' value='".$assigned_id."' name = 'like' type='submit'><span class = 'buttons'>Like</span><span class='glyphicon glyphicon-heart'></span></button>";
//Problem 1: I want whenever the next button with the class 'mmore' is clicked, the class
'comment_data' should be displayed. It is set to "display:none" by default but
whenver I click it, all other comment are displayed.
echo "<button class='mmore pacedown' value='".$post_id."' name = 'more' type='submit'><span class = 'buttons'>More</span><span class='glyphicon glyphicon-chevron-down'></span></button>";
echo " "."<span class = 'slanted'>". $time . "</div>";
echo "</form>";
// fetch and display comment for each post...
$qry = "SELECT user_id, comment FROM comments WHERE post_id = ? ORDER BY time DESC";
$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));
$q->bindParam(1, $post_id);
$q->execute();
if($commentz = $q->fetchAll()){
echo "<div class = 'comment_data'>";
foreach ($commentz as $comment){
echo "<div class = 'per_comment'>";
echo "<p>". $comment[0] ." ". $comment[1] . "</p>";
echo "</div>";
}
echo "</div>";
}?>
<form method='post' class='murconform form-horizontal' name='signinform' action ='<?php echo htmlentities($_SERVER['PHP_SELF']);?>'>
<?php
echo "<div class = 'commentdiv'>";
echo "<input type='hidden' name='post_id' value='".$post_id."'>";
echo "<textarea autocomplete = 'off' name='commentdata' maxlength='480' class='commenttext form-control' rows = '1' placeholder='Have your say...'></textarea>";
echo "<span class='counter_msg'></span>";
echo "<button class='btn btn-xs btn-primary onespacedown comment' name = 'comment' type='submit'>Comment</button>";
// Problem 2: How do I get the content of this textarea whenever the submit button is clicked via AJAX?
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
This is my jQuery code for Problem 1:
$( ".comment" ).click(function() {
var $this=$(this);
$(".murconform").submit(function(e){
return false;
});
$('.comment_data').slideToggle("slow");
});
And this is the AJAX code for Problem 2:
$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var $this=$(this);
var post_id = $('.post_id').val();
var comment = $(".commentdata").text();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: { post : post_id , comment : comment },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.comment').html( msg );
});
});
Any good solution/advice(with regards to best practice) would be deeply appreciated.
Hard to know for sure unless you post the generated HTML, not the code that generates it but it seems that what you are trying to do is target elements within a group, not those outside of that group that have the same class name.
To do this you find a common parent of those elements (for example a div that wraps those elements), in your case .feeds seems to occur once per iteration.
$('.mmore').on('click', function(){
var $commonparent=$(this).closest('.feeds');
Then you find the elements you want within $commonparent
var post_id = $commonparent.find('.post_id').val();
var comment = $commonparent.find(".commentdata").text();
This might clear up both problems. For a better answer please post the generated HTML and move your problem explanations to outside of the code.
To clarify, div.feeds can be used as the closest ancestor allowing you to find child elements by class name that only exist within that particular div.feeds
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>
Related
I have a JavaScript like counter that works on the 1st comment but the 2nd comment, I would appreciate any help given!
This keeps happening wether I use PHP or JavaScript, here is my JavaScript for the counter
var count = (function()
{
var counter = 0;
return function() {return counter +=1;}
})();
function displaycount()
{
document.getElementById("carrier").innerHTML = count();
}
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$id = $row['uid'];
$sql2 = "SELECT * FROM users WHERE id='$id'";
$result2 = $conn->query($sql2);
if ($row2 = $result2->fetch_assoc()) {
echo "<div class='comment-box'><p>";
echo $row2['first_name']."<br>";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "<br>
<img src='image.ico' onclick='displaycount()'>
<p id='carrier'> 0 </p>";
echo "</p>";
if (isset($_SESSION['id'])) {
if ($_SESSION['id'] == $row2['id']) {
echo "<form class='delete-form' method='POST' action='".deleteComments($conn)."'>
<input type='hidden'
name='cid'
value='".$row['cid']."'>
<button type='submit' name='commentDelete'>
Delete
</button>
</form>";
} else {
echo "<form class='edit-form' method='POST' action='replycomment.php'>
<input type='hidden'
name='cid'
value='".$row['cid']."'>
<input type='hidden'
name='uid'
value='".$row['uid']."'>
<input type='hidden'
name='date'
value='".$row['date']."'>
<input type='hidden'
name='reply'
value='".$row['reply']."'>
<button>Reply</button>
</form>";
}
} else {
echo "<p class='commentmessage'>You need to be logged in to reply</p>";
}
echo "</div>";
}
}
}
The reason that only the first comment is updating is you using the id carrier in all your comments.
The way to fixed this is:
Change the following line in your PHP code
<p id='carrier'> 0 </p>
to
<p id="carrier-"'+$id+'"> 0 </p>
Note: try not expose the entity id, try to use another column in comment table, that is unique for each comment.
Change the click of the element, passing the column that you use in previous step, like this
<img src='image.ico' onclick='displaycount('.$id.')'>
Change your javascript function to
function displaycount(id) {
document.getElementById("carrier-"+id).innerHTML = count();
}
If you have a question, please leave a comment
I already get the id from a php loop for my checkboxes, and pass them as a string(maybe not because I could not split them with comma) in parameter, then I need to check if the checkbox is checked in javascript using the ids I passed through.
It doesnt seem like I can split it in javascript as well, and after I ran the for loop, the data is undefined in the new string.
Do you have any ideas? Please help
here is my php
echo "<div id='addstock'>";
$ids = '';
while($row_add = mysqli_fetch_array($result_add)){
$id=$row_add['id'];
$company = $row_add['companyname'];
//create checkbox for company
echo "<p class='checkbox'><input type='checkbox' name='stocks' id='".$id."' value='".$id."'>".$company."</p><br>";
$ids .= $id;
}
echo "</div>";
echo "<p class='input'><input type='submit' class='submitbutton' value='Submit' onclick='updatetable(".$ids.",".$user.")'></p>";
here is my javascript
//update table after add to stock
function updatetable(ids,user){
var url = "update.php";
//var res= ids.split(" ");
alert(ids);
var stocks = "";
//check if the checkbox is checked
for(var id in ids){
if(document.getElementById(ids[id]).checked)
{
stocks += ids[id];
alert(ids[id]);
}
}
//alert(stocks);
var data = "ids="+stocks+"&user="+user;
alert(data);
ajaxRequest(url, "POST", data, true, proceedUpdate);
}
function proceedUpdate(response){
target_div = document.getElementById("tablediv");
target_div.innerHTML = response;
}
Try this:
<div id="addstock">
<?php
$ids = array();
while($row = mysqli_fetch_array($result_add)) {
$ids[] = $row_add['id'];
echo '<p class="checkbox"><input type="checkbox" name="stocks" id="' . htmlspecialchars($id) . '" value="' . htmlspecialchars($id) . '">' . htmlspecialchars($company). '</p><br>' . "\n";
}
?>
</div>
<p class="input">
<input type="submit" class="submitbutton" value="Submit" onclick="updatetable('<?php echo htmlspecialchars(implode(',', $ids)); ?>', '<?php echo htmlspecialchars($user); ?>')">
</p>
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 have displayed 4 rows of a table (gids) from phpmyadmin.
Now I have added for each row a button, I want to redirect each button to an external page (book.php). Now when I use the classname "data" in javascript to try to redirect to book.php, this doesn't work for all 4 buttons.
What should I change so these buttons work for each row?
<div class="row">
<?php
if(isset($_SESSION['FBID'])){
// Create connection
$conn = new mysqli("localhost", "root", "root", "phpproject");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT gids_voornaam, gids_naam, gids_bio, gids_richting, gids_jaar, gids_stad FROM gids";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
'<div class="col-sm-4">'.
"<br>".'<img class="img-rounded img-responsive" src="http://placehold.it/150">'.
"<br>"."voornaam: ".$row["gids_voornaam"].
"<br>". "Achternaam: ". $row["gids_naam"].
"<br>". "Richting: ". $row["gids_richting"].
"<br>". "Jaar: ". $row["gids_jaar"].
"<br>". "Biografie: " . $row["gids_bio"].
"<br>"."<br>".'<button type="submit" class="data" >boekingsdata</button>'.
'</div>';
}
} else {
echo "0 results";
}
$conn->close();
}
?>
</div>
<script>
var btn = document.getElementsByClassName('data');
btn.addEventListener('click', function() {
document.location.href = 'book.php';
});
</script>
var btn is an array so you need to read as an array.
Try this:
var btn = document.getElementsByClassName('data');
for(var item in btn){
btn[item].addEventListener('click', function() {
document.location.href = 'book.php';
});
}
If I correctly understood your code, the result will be four rows, and each have a button at the end, right?
Because there is your problem: all buttons have the same ID: id="dat"
You can avoid this by creating a new variable to count the rows, then append the variable's value to each buttons ID, thus creating "dat1", "dat2", etc.
Modify this part:
// output data of each row
while($row = $result->fetch_assoc()) {
echo
'<div class="col-sm-4">'.
"<br>".'<img class="img-rounded img-responsive" src="http://placehold.it/150">'.
"<br>"."voornaam: ".$row["gids_voornaam"].
"<br>". "Achternaam: ". $row["gids_naam"].
"<br>". "Richting: ". $row["gids_richting"].
"<br>". "Jaar: ". $row["gids_jaar"].
"<br>". "Biografie: " . $row["gids_bio"].
"<br>"."<br>".'<button type="submit" id="dat" class="data" >boekingsdata</button>'.
'</div>';
}
Into this:
// output data of each row
$counter = 1; //new variable
while($row = $result->fetch_assoc()) {
echo
'<div class="col-sm-4">'.
"<br>".'<img class="img-rounded img-responsive" src="http://placehold.it/150">'.
"<br>"."voornaam: ".$row["gids_voornaam"].
"<br>". "Achternaam: ". $row["gids_naam"].
"<br>". "Richting: ". $row["gids_richting"].
"<br>". "Jaar: ". $row["gids_jaar"].
"<br>". "Biografie: " . $row["gids_bio"].
"<br>"."<br>".'<button type="submit" id="dat' . $counter . '" class="data" >boekingsdata</button>'.
'</div>';
$counter++; //increment it with every row
}
Try this
var btn = document.getElementById('data');
also change your button to
id='data'
and in function
window.location.href = 'book.php'; // here also try to give full url
Try this instead:
var btn = document.getElementById('dat');
btn.addEventListener('click', function() {
document.location.href = 'book.php';
});
UPDATE Based on your comments:
1 - You'll need to build a form, example:
<html>
<body>
<form action="book.php" method="post">
voornaam: <input type="text" name="voornaam" value="<?php echo $row["gids_voornaam"]?>"><?php echo $row["gids_voornaam"]?><br>
etc..
<input type="submit">
</form>
</body>
</html>
2 - After the user clicks the submit button, you'll need to get the POST values on book.php, example:
voornaam IS <?php echo $_POST["voornaam"]; ?><br>
You don't need javascript for this, just simple html and php on backend.
I posted this code minutes 15 mins ago and I did get help for the preventDefault issue , but now I'm not getting my alerts to work , yet firebug doesn't show any error related to this code .. May i ask where I'm going wrong ,
<?php
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Expires: Sat 26 Jul 1997 05:00:00 GMT"); // Date in the past
require_once ("../_includes/functions.php");
?>
<link rel="stylesheet" title="Style CSS" href="../_reports/report_assets/cwcalendar.css" type="text/css" media="all" />
<script src="../_js/jquery-1.6.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../_js/timer.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="../_reports/report_assets/calendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select').click(function(event){
$(':checkbox').prop("checked", true);
event.preventDefault();
});
$('#deselect').click(function(event){
$(':checkbox').prop("checked", false);
event.preventDefault();
});
$('#add').click(function() {
var field = '<input class="project_fields" type="text" size ="30" name = field_settings[] /> ';
var checkbox = '<input class ="checkbox" type ="checkbox" name ="check_field[]" /> ';
var delete_link = '<a class ="delete_link" style="text-decoration:none;" href="#"> Delete field </a> <br /><br />';
var input = field + checkbox + delete_link;
$('#input_fields').append(input);
});
$('#project_fields_submit').click(function(event) {
event.preventDefault();
var array_fields = new Array();
$('.checkbox').each(function() {
if($(this) .is(':checked')) {
array_fields.push('1');
alert('checked!!!');
}
else {
array_fields.push('0');
alert('not checked !!!')
}
});
$('#checkboxes').val(array_fields);
});
$('#edit_fields_submit').click(function(event) {
event.preventDefault();
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
});
var nextRowID = 0;
$('#add_edit').click(function() {
var id = ++nextRowID;
var new_field = '<input class ="class'+id+'" type="text" size ="40" name = edit_field_value[] value =""> ';
var new_checkbox = '<input class ="class'+id+'" type ="checkbox" name ="check_field[]" > ';
var delete_edit = '<a id ="'+id+'" class ="new_delete_edit" style="text-decoration:none;" href="#" > Delete field </a><br><br>';
var new_input = new_field + new_checkbox;
$('#new_input_fields').append(new_input);
$('#new_input_fields').append(delete_edit);
});
$('a.delete_edit').click(function(event) {
event.preventDefault();
var ID = $(this).attr('id');
var delete_field_id = 'edit_field'+ID;
var field_data = $('#'+ delete_field_id).val();
var project_id = $('#edit_project_id').val();
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/delete_field.php",
data: string,
success: function(data){
$('#'+ID).remove();
$('#'+delete_field_id).remove();
$('#new_check'+ID).remove();
}
});
});
$('.new_delete_edit').live('click', function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.class'+id).hide();
$('#'+id).hide();
});
});
</script>
<?php
if (isset($_GET['pid']) && isset($_GET['user_id'])) {
$id = $_GET['user_id'];
$pid = $_GET['pid'];
$show_id = $_GET['show_id'];
"
$query_settings ="SELECT project_settings FROM projects WHERE project_id ='$pid'";
$result_settings = mysql_query($query_settings);
$row_settings = mysql_fetch_array($result_settings,MYSQL_ASSOC);
if($row_settings['project_settings'] == NULL) {
echo "<h2> Project Settings </h2>";
echo "<br><br>";
echo " <b> Add fields </b>";
echo " ";
echo "<img id ='add' src='_assets/add.png' /><br><br><br>";
echo '<form action ="" method="post">';
echo'<input type="hidden" name="pid" value="'.$pid.'">';
echo "<input id ='checkboxes' type ='hidden' name ='checkboxes' value ='' >";
echo "<div id='input_fields'> </div>";
echo '<input id ="project_fields_submit" type ="submit" name ="project_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
echo "<br><br><br><br><p></p>";
}
else {
echo "<h2> This Project Settings </h2>";
echo "<br><br><br><br>";
echo "<b> Add fields</b> <img id ='add_edit' src='_assets/add.png' /><br><br><br>";
$fields_data = unserialize($row_settings['project_settings']);
$i = 0;
echo '<form action ="" method="post">';
echo'<input id ="edit_project_id" type="hidden" name="edit_project_id" value="'.$pid.'">';
echo "<div id='new_input_fields'> </div>";
echo "<input id ='edit_checkboxes' type ='hidden' name ='edit_checkbox' value ='' >";
foreach ($fields_data as $key => $value) {
if($value =="1") {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size ='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' checked /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
} else {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
}
$i++;
}
echo '<input id ="edit_fields_submit" type ="submit" name ="edit_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
}
echo '</div>';
echo '<div id="project-setting-results"></div><div class="clear"></div>';
echo '</div><!-- end fragment-6 -->';
}
?>
I suggest changing your design. Using <form> codes and posting isn't always the best way of sending your data to another (or the same) page for PHP processing. Instead, switch over to using AJAX code to submit your form.
For one thing, this will allow you to get away from the e.preventDefault kludges. A number of things will iron themselves out if you use the AJAX approach (instead of submitting a form). I can see that you're already using AJAX in your code, but if you're still uncomfortable with it you can check out these other answers:
Form not posting correctly
Place PHP results inside HTML Page
Update data in a DIV
Change your #edit_fields_submit input field from type="submit" to type="button" and use javascript/AJAX to:
Get all the values you would normally submit as a <form>;
Use AJAX to submit them to a PHP file for processing
In the success: function of the AJAX code block, use javascript to send the user over to whatever page you want them to see next
Example:
$('#edit_fields_submit').click(function(event) {
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
var field_data = //you know how to get these values
var project_id = //etc
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/myprocessor.php",
dataType: "json",
data: string,
success: function(data){
document.location.href='yournewpage.php';
}
});
});