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.
Related
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);
}
});
})
I want ajax to update two different things. one is the clicked button class, and second is database record in while loop
Home
<?php
$q = mysqli_query($cn, "select * from `com`");
while ($f = mysqli_fetch_array($q)) {
?>
com: <?php echo $f['com']; ?><br>
<?php
$q1 = mysqli_query($cn, "select * from `fvc` where m_id='" . $f['id'] . "' and log='" . $_SESSION['id'] . "'");
$q2 = mysqli_query($cn, "select * from `fvc` where log='" . $_SESSION['id'] . "'");
?>
<span class="result<?php echo $f['id']; ?>">
<?php if (mysqli_num_rows($q1) > 0) { ?>
<button value="<?php echo $f['id']; ?>" class="unfc"><i title="<?php echo mysqli_num_rows($q2); ?>" class="fa fa-star" aria-hidden="true"></i></button>
<?php } else { ?>
<button value="<?php echo $f['id']; ?>" class="fc"><i title="<?php echo mysqli_num_rows($q2); ?>" class="fa fa-star-o" aria-hidden="true"></i></button>
<?php } ?>
</span>
<?php
}
?>
AJAX
$(document).ready(function(){
$(document).on('click', '.fc', function(){
var id=$(this).val();
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: id,
vote: 1,
},
success: function(){
showresult(id);
}
});
});
$(document).on('click', '.unfc', function(){
var id=$(this).val();
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: id,
vote: 1,
},
success: function(){
showresult(id);
}
});
});
});
function showresult(id){
$.ajax({
url: 'result.php',
type: 'POST',
async: false,
data:{
id: id,
showresult: 1
},
success: function(response){
$('.result'+id).html(response);
}
});
}
result.php
<?php
session_start();
include('cn.php');
if (isset($_POST['showresult'])){
$id = $_POST['id'];
$q3=mysqli_query($cn, "select * from `fvc` where m_id='".$id."' and log='".$_SESSION['id']."'");
$q4=mysqli_query($cn,"select * from `fvc` where log='".$_SESSION['id']."'");
$numFavs = mysqli_num_rows($q4);
if (mysqli_num_rows($q3)>0){
echo '<button class="unfc" value="'.$id.'"><i title="'.$numFavs.'" class="fa fa-star" aria-hidden="true"></i></button>' ;
} else {
echo '<button class="fc" value="'.$id.'"><i title="'.$numFavs.'" class="fa fa-star-o" aria-hidden="true"></i></button>' ;
}
}
?>
total number of row response is not updating for all comments in while loop.
I want loop ids to be updated as well in Ajax response for each comment So guide me whats wrong in my code
Your success function is targetting an element by ID, so a single specific element on the page. If you want to update multiple values you need to target a class or an element type which is common to the elements you want to target.
You have two classes for the buttons, so you could use those. You would have to change your PHP output so it just returns the new total number of likes, no HTML output needed.
Your success function in showLike would look something like this:
$(':button[value="'+id+'"]').toggleClass('favcom unfavcom');
$('.unfavcom').html('<i title="Remove from Favorite? - ('+response+'/20)" class="fa fa-star" aria-hidden="true"></i>');
$('.favcom').html('<i title="Favorite Comment - ('+response+'/20)" class="fa fa-star" aria-hidden="true"></i>');
Ofcourse it will update only one element, your show_like function updates only one element, the one with id = #show_like'+id
if you want to update all span elements, create a function update_likes() and call it in the success instead of show_like(),
$(document).on('click', '.favcom', function(){
var id=$(this).val();
$.ajax({
type: "POST",
url: "like.php",
data: {
id: id,
like: 1,
},
success: function(){
update_likes('.favcom');
}
});
});
then loop through the span elements and update each one of them, you can add a class .show_like if you have other spans and instead of $("span") put your class,
function update_likes(class){
$(class).each(function() {
show_like( $(this).val() );
});
}
i hope this works, however, this is based on your code and it will make a lot of http requests ( in show_like() ) and i would recommend you improve it by trying to return all the data you need and loop through an array instead of making Ajax calls every time.
I have been trying to delete a row in my mySQL database on the onclick of a delete button. But instead of the one mySQL row getting deleted, all rows in the database get deleted.
I am targeting just the specific ID, so I am unclear as to why all other ID's are getting deleted.
HTML:
<?php foreach ($movies as $movie) : ?>
<div class="col-4">
<div class="card card-cascade">
<div class="view gradient-card-header purple-gradient">
<h2><?php echo $movie['name']; ?></h2>
<p><?php echo $movie['genre']; ?></p>
</div>
<div class="card-body text-center">
<!-- Delete -->
<a type="button" class="btn-floating btn-small btn-dribbble delbutton" data-toggle="tooltip" data-placement="top" title="Delete" id="<?php echo $movie['id']; ?>"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
</div>
</div>
</div>
<?php endforeach; ?>
JS:
$(function () {
// Tooltips Initialization
$('[data-toggle="tooltip"]').tooltip();
// Delete Movie
$(".delbutton").click(function() {
console.log('watch me')
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "../movieApp/delete.php", //URL to the delete php script
data : {id:info},
success : function() {
console.log("success");
},
error: function () {
console.log("failed");
},
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
PHP:
require 'config/config.php';
require 'config/db.php';
if($_POST['id']){
$id=$_POST['id'];
$delete = "DELETE FROM movies WHERE id=$id";
$result = $conn->query($delete);
}
if (mysqli_query($conn, $sql)) {
mysqli_free_result($result);
mysqli_close($conn);
echo "Worked!";
exit;
} else {
echo "Error deleting record";
}
You set ajax method POST, But Post data format is not correct as per your requirement.
Change your ajax Data like as
//var info = 'id=' + del_id;
var info = {
id : del_id
}
And
$.ajax({
/*...*/
data : info,
/*.../
});
And also check if your id field is string, If integer then change the Query string to -
#$delete = "DELETE FROM movies WHERE id='$id'";
$delete = "DELETE FROM movies WHERE id=$id";
Also change -
#$_POST['info']
$_POST['id']
Because, You didn't set $_POST['info'] anywhere in your code.
Note : And don't forget to console your correct Ajax URL
In your HTML use data-id="<?php echo $movie['id']; ?>" for the tag. Then in your JS you can pick up the value like so: var del_id = $(this).data("id");. I would also inspect element in your browser to see if you are in fact sending an "id" to your PHP script. If you are then possibly you may want to enable error debugging in your PHP script like so: error_reporting(E_ALL);
ini_set('display_errors', 1);. Also wouldn't hurt to change your SQL statement to something like this: $delete = "DELETE FROM movies WHERE id='" . $id . "'";. Good luck with this one doesn't sound too hard.
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>
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();
});