How to refresh a div on link or button click? - javascript

I am working on a small social network project where I am using post comment functionality. What I am stuck with is as soon as the use deletes a comment, the comment count should decrease automatically. This can onyl be done using refresh functionality, but the current code does not seem to be working. It deletes the comment but does not display the decreased count. So whenever a comment is deleted, it should show up the decreased count. Here is my code so far.
<div style="border:2px solid red;" class="comment_ui" id="view<?php echo $id; ?>">
<div>
View all <?php echo $comment_count; ?> comments
</div>
<div class="comment_ui">
<div class="comment_text">
<div class="comment_actual_text">
<?php echo $FirstName.' '.$LastName;?>
<a id="<?php echo $c_id;?>" class = "delete_comment" style="position: relative; float:right; right: 20px; text-decoration: none;" href="#">x</a><p/>
<div id="sssss"><?php echo $comment; ?></div>
</div>
</div>
</div>
JQuery
<script type="text/javascript">
$(function(){
$(".delete_comment").click(function(){
var element = $(this);
var comment = element.attr("id");
var commentRow = $(this).closest('.comment_text');
var info = "comment="+comment;
$.ajax({
type: "POST",
url: "delete_comment.php",
data: info,
success: function(){
commentRow.fadeOut('slow', function() {$(this).remove();});
$('.comment_ui').load(url + ' .comment_ui');
}
});
return false;
});
});
</script>

Try Below code
<script type="text/javascript">
$(function(){
$(".delete_comment").click(function(){
var element = $(this);
var comment = element.attr("id");
var commentRow = $(this).closest('.comment_text');
var info = "comment="+comment;
$.ajax({
type: "POST",
url: "delete_comment.php",
data: info,
success: function(){
commentRow.fadeOut('slow', function() {$(this).remove();});
$.post( url + ' .comment_ui', function( data ) {
$( ".comment_ui" ).html( data );
})
},
error: function(){
alert("somthing is wrong")
},
});
});
});
</script>

You cant use .load() like that. The variable url isn't defined and you can't add a jquery selector to the url.
If you cant .load() the exact html you need you must .get() it instead, .find() the part you need in the response and insert it with .html()
EDIT: Added code suggestion
<div style="border:2px solid red;" class="comment_ui" id="view<?php echo $id; ?>">
<div>
<a href="#" class="view_comments" id="<?php echo $id; ?>">View all
<span id="totalCommentsCount"><?php echo $comment_count; ?></span> comments</a>
</div>
<div class="comment_ui">
<div class="comment_text">
<div class="comment_actual_text">
<?php echo $FirstName.' '.$LastName;?>
<a id="<?php echo $c_id;?>" class = "delete_comment" style="position: relative; float:right; right: 20px; text-decoration: none;" href="#">x</a><p/>
<div id="sssss"><?php echo $comment; ?></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$(".delete_comment").click(onDeleteComment);
});
function onDeleteComment() {
var commentElement = this;
var commentId = commentElement.id;
//Start the fade-out even before the delete is committed to create a fast user experience
var commentRow = $(commentElement).closest('.comment_text');
commentRow.fadeOut('slow', function() { commentRow.remove(); });
//Post the delete to the server
$.ajax({
type: "POST",
url: "delete_comment.php",
data: { comment: commentId },
success: function (deleteResponse) {
//USE ONE OF THE ALT. BELOW:
//Alt.1: delete_comment.php returns a json like { count: 12 } which describes number of comments left
$('#totalCount').text(deleteResponse.count);
//Alt.2: you don't care to reload number of comments from server and just decrease by one.
var totalCountSpan = $('#totalCount');
totalCountSpan.text(parseInt(totalCountSpan.text()) - 1);
//Alt.3: get number of comments left on server by reloading the "view" an extra time. Really not optimal!
var viewId = $('.comment_ui').attr('id');
$.get( "get_view.php?id=" + viewId, function( data ) {
var newCount = $(data).find('#totalCount').text();
$( "#totalCount" ).text( newCount );
});
},
error: function(){
//Possibly restore the comment here if this happens often?
alert("somthing is wrong")
},
});
}
</script>

Related

How To Retain or keep hidden div element after page reloaded?

I have a hidden div on my page, I want to know what kind of way I can do to keep showing the div when the page is reloaded, with the following example:
This my html :
<div class="card-body">
<div class="overlay" id="kt_datatable_nodata">
<div class="overlay-wrapper rounded bg-light text-center">
<p class="font-weight-bold text-center">Pilih data untuk dibandingkan</p>
<a href='#right-modal' class='btn' data-toggle='modal'>Change Data</a>
</div>
</div>
<!--begin::Table-->
<div id="kt_datatable_fetch_display"></div>
<!--End::Table-->
</div>
This My javascript :
$('#kt_datatable').on('click','tr button', function() {
var id = $(this).data('id');
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/right-side/right-value.php',
data: {
'rowid': id
},
success: function(data) {
$('#kt_datatable_nodata').addClass('hidden');
$('#kt_datatable_fetch_display').html(data);
}
});
})
this right-value.php :
<?php
session_start();
include 'db_connect.php';
if (isset($_POST['rowid'])) {
$id = $_POST['rowid'];
$query = mysqli_query($config, "SELECT* FROM data_penilaian where id = '$id'");
$no = 1;
while ($row = mysqli_fetch_array($query)) {
?>
<form class="leftForms" method="POST">
<input type="hidden" name="id" value="<?= $row['id']; ?>">
<input type="text" name="position" value="<?= $row['position']; ?>">
</form>
<?php
}
} ?>
here what I want to do is what kind of way I can do to keep the kt_datatable_fetch_display on or after the page is reloaded. Thanks for any help.
I dont know if I understand quite what you want to do, but the only way I'm thinking you could achieve this it's to make your button to add a query param that must be your id.
Exaple:
// This goint to redirect to the new URL
$('#kt_datatable').on('click','tr button', function() {
var id = $(this).data('id');
var yourSiteURL = "http://localhost";
window.location.href = `yourSiteURL/${id}`;
});
/*
When DOM loads read query params and make your ajax req
So, no matter page reloads, always goint to make the ajax req and fill your div
*/
$(document).ready(function(){
var searchParams = new URLSearchParams(window.location.href);
var id = searchParams.get("id");
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/right-side/right-value.php',
data: {
'rowid': id
},
success: function(data) {
$('#kt_datatable_nodata').addClass('hidden');
$('#kt_datatable_fetch_display').html(data);
}
});
})

How to get ajax response using custom attribute in php loop

I am working with ajax with php,I have following buttons in loop,I just want to
show/fetch data(number) on correct place/div using "attr" in jquery but not working in my side
Here is my button in loop
<?php
foreach //
<button class="btn likebutn_r" data-datac="1" data-datacw="<?php echo $WalletAddress; ?>" data-datacr="<?php echo $rev->id; ?>" data-datacoin="<?php echo $rev->coin_id; ?>" data-datasymbol="<?php echo $rev->symbol; ?>" id="show<?php echo "1";?>" value="1" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumb.png" height="24" width="24"></button>
<div id="<?php echo $rev->id; ?>">12(dynamic)</div>
endforeach//
Here is my ajax code,How can i get data using custom attribute (via pass ReviewId)? Thanks in advance
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function (e) {
var vote = $(this).data('datac');
var review = $(this).data('datacr');
var CoinId = $(this).data('datacoin');
var symbol = $(this).data('datasymbol');
var WalletAddress = $(this).data('datacw');
var datacrp = $(this).data('datacrp');
$('#' + review).hide();
e.preventDefault();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>main/AddVote',
data: {
vote: vote,
review: review,
CoinId: CoinId,
symbol: symbol,
WalletAddress: WalletAddress
},
success: function (data) {
alert(data);
$('#' + review).html(data);
}
});
});
});
</script>
Hope this code help you.
*Reminder the js code below have to implement inside the php file so the Post url ajax will get the value.
$('body').on('click', '.btn', function(e){
var allData = {
"vote": $(this).data('datac'),
"review": $(this).data('datacr'),
"CoinId": $(this).data('datacoin'),
"symbol": $(this).data('datasymbol'),
"WalletAddress": $(this).data('walletaddress'),
}
e.preventDefault();
$.ajax({
type: 'POST',
url:'test.com',
data: allData,
success: function(data) {
$(this).attr('data-datac', data['vote']);
$(this).attr('data-datacr', data['review']);
$(this).attr('datacoin', data['CoinId']);
$(this).attr('data-datasymbol', data['review']);
$(this).attr('data-datacoin', data['review']);
$(this).attr('data-datasymbol', data['symbol']);
$(this).attr('data-walletaddress', data['WalletAddress']);
}
});
});
<button
class="btn likebutn_r"
data-datac="1"
data-datacw="teste"
data-datacr="asdfasf"
data-datacoin="asdfasdf"
data-datasymbol="asdfasdf"
data-datacrp="asfsa"
id="31"
data-walletaddress="dsaf"
value="1"
type="submit">Hello</button>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>

jQuery only firing once

I got one problem: My jQuery ist only firing once:
<script type="text/javascript">
$(function() {
$('#delcat').click(function() {
var elem = $(this);
var parents = $('.did' + elem.attr('data-catid'));
var parents2 = $('.did2' + elem.attr('data-catid'));
$.ajax({
type: 'get',
url: 'del_name.php',
data: 'id=' + elem.attr('data-catid'),
beforeSend: function() {
elem.animate({ 'backgroundColor': '#fb6c6c' }, 400);
parents2.animate({ 'backgroundColor': '#fb6c6c' }, 400);
},
success: function() {
parents.fadeOut("slow");
}
});
return false;
});
});
</script>
I can delete only the first "item". After that it needs a refresh and than I can delete the next first "item" again. Very confusing.
This is how the "items" are displayed:
<? foreach($stmt as $row) { ?>
<div class="col-lg-3 col-xs-6 did<?php echo $row[0]; ?>" id="row1">
<div class="small-box bg-aqua">
<div class="inner did2<?php echo $row[0]; ?>">
<p>Name</p>
<h2><? echo $row[1]; ?></h2>
</div>
</i>
</div>
</div>
<? } ?>
You can have one unique id on a single page; since you're looping through $stmt, you can't be using id multiple times. Replace the id with a class and bind that
PHP -- Loop
</i>
And JS changes.
$('.delcat').click(function(){
....
});
Use class to do that things:
$('.delcat').click(function(){
instead of
$('#delcat').click(function(){
In your html:
</i>
Your solution get the first element with that id. You never have to use multiple equal id.

Auto refresh controller and view Yii

How i could make this page auto refresh/update every 10 second when there is/isnt data update. Like Twitter when there is a new tweet.
Example : This is in first second.
You have 1 name with no status
Then after 10 second, there is an event that "name" data have been added.
You have 2 names with no status
what should i do? I've tried with javascript, but it wont refresh the data from controller.
this is my actioncheckNames Controller
public function actioncheckNames() {
//Check Name with No Status
$noStat = new CDbCriteria();
$noStat->condition = "status IS NULL";
$noStat->order = "name ASC";
$sums = Name::model()->count($noStat);
//End of Check Function
return array('sum'=>$sums);
}
And this is sort of my index on view.
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: '<?php echo $this->createUrl('name/checkNames'); ?>'
, type: 'post'
, success: function(data) {
if (data) {
$("#checkname");
}
}
});
}, 5000 //5 seconds
);
});
</script>
<div id="checkname">
<?php
if ($sum != 0) {
?>
<div class="alert alert-block alert-primary fade in">
<button data-dismiss="alert" class="close" type="button">X</button>
<h4 class="alert-titleing">You Have <?php echo $sum ?> Names With No Status. <font color="White"><u>Check</u></font> </h4>
</div>
<?php }
?>
</div>
*Update : create actionCheckNames Controller and add ajax script. but my web wont refresh the data.
You can refresh your page by JS set interval + AJAX request & can try something like below
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: '<?php echo $this->createUrl('controller/action');?>'
,type: 'post'
//,data: {var1: val1, var2: val2,....}
,success: function(data){
if(data){
//Refresh your div/html element by appending here...
}
}
});
},10000 //10 seconds
);
});

Removing div created from PHP using jQuery

How do I use jquery to remove this div tag created in php? Specifically, After pressing the delete button I want to remove one div. I have several.
Here is my PHP code:
<?php
// For each book...
while ($row = mysql_fetch_assoc($result)){
echo '<div class="task-list" id="div_'.$row['uid'].'"><table>';
echo "<tr>";
echo "<td><b>".$row['title']."</b></td></tr>";
echo "<tr><td>".$row['author']."</td></tr>";
echo '<tr><td><img src="'.$row['image_url'].'" width="50" height="100" /></td></tr>';
echo '<tr><td><button class="btn cmt_list" name="cmtList" id="cmt- '.$row['uid'].'"value = "hide/show"/>Show</button> </td></tr>';
echo '<tr><td><button class="btn btn-danger delete_bk" name="deleteItem" id="'.$row['uid'].'" />Delete</button></td></tr>';
echo "</table></div>";
?>
This is my javascript:
//deleting a book from DB when user clicks "Delete" button
$(".delete_bk").on("click", function() {
var book_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "delete_bk.php",
data: {book_id: book_id}
})
.done(function() {
var id = $(this).attr('id');
$('#div_'+id).remove();
alert("Data deleted");
});
});
Which div you would delete?
In jQuery you can simply do:
$(div_to_remove).remove();
try this one
$(".delete_bk").on("click", function() {
var book_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "delete_bk.php",
data: {book_id: book_id},
success:function(){
$('#div_'+book_id).remove();
alert("Data deleted");
}
})
});
try this
$("#deletebtnid").click(function(e){
$("#divid").remove();
});
$('.task-list').remove();
and if you just want to remove the first div:
$('.task-list').first().remove();
you can add the following code somewhere in your html:
<script>
$(document).ready(function() { $('.task-list').remove(); });
</script
Note:
start with . for class names and # for ids to find elements in jQuery.
Example: $('.YOURCLASSNAME') or $('#YOURID')
try this code
$(document).on('click','.delete_bk', function(){
$('#bookdiv').remove();
});
Try this
$(document).on('click', '.delete_bk', function(){
var id = $(this).attr('id');
$('#div_'+id).remove();
});
Here in line,
<div class="task-list" id="bookdiv"><table>
you need to apply ID like
<div class="task-list" id="div_'.$row['uid'].'"><table>
seems that you have the id "bookdiv" more that once - html ids have to be unique... change div -> add a data-attribute like data-delete="$id_of_your_div" to your button and then:
Example
Html:
<div class="bookdiv task-list" id="book-5813">
Button:
<button class="delete_bk" ... data-delete="#book-5813" />
Delete JS
$(document).on('click','.delete_bk', function(){
var delete = $(this).data('delete');
$(delete).remove();
});

Categories

Resources