Removing div created from PHP using jQuery - javascript

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();
});

Related

Changing logic - jQuery

I have buttons that add and remove products from the Magento cart, but that's not so relevant in that issue. What I want to do is change the logic of what they are doing. Currently, when the buy button is clicked, the product is added to the cart, the button is "changed" to remove it and all other buttons are disabled for the click. When the remove button is clicked, the product that was added is removed and all other buttons can be clicked again.
I want to change the logic to the following: when the buy button is clicked, the product is added to the cart and the buy button is "changed" to remove (so far everything is the same as it was). But, all buttons remain click-enabled and if any other buy button is clicked, the product that was added is removed and the new product is added.
I've researched and thought in many ways, but I can not find a way to do that.
Button code:
<button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Add to Cart')) ?>" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<button style="display: none;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remover</span></span></button>
Ajax requisition code:
function addCartao(product_id){
$j('#cartaoMensagem'+product_id).hide();
$j('#cartaoMensagemRemover'+product_id).show();
$j('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product_id: product_id
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product_id);
$j('#cartao').find(':button').not(button).attr('disabled',true);
$j('.item-custom').append('<tr id="trAppend"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
window.location.reload();
history.go(0);
window.location.href=window.location.href;
}
});
}
function removeCartaotoCart(itemId){
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId);
$j('#cartao').find(':button').attr('disabled',false);
$j('.item-custom #trAppend').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
window.location.reload();
history.go(0);
window.location.href=window.location.href;
}
});
}
I "simplified" your code a lot... Since I can't make an example with your PHP.
So the "reproduced" behavior is in this CodePen.
Now what you need to do, is to keep the added product ID in "memory" in a variable.
On add... If there already is a product ID, call the remove function, then add the other product.
It should be as simple as this.
So here is another CodePen with th modifications to make.
var productSelected = ""; // The variable used as a "memory".
function addCartao(product_id){
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
console.log("Add "+product_id);
productSelected = product_id; // Keep the product id in "memory".
$('#cartaoMensagem'+product_id).hide();
$('#cartaoMensagemRemover'+product_id).show();
$('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000','color':'white'});
//Ajax...
// In the success callback:
var button = $('#cartaoMensagemRemover'+product_id);
//$('#cartao').find(':button').not(button).attr('disabled',true); // Do not disable the other buttons.
}
function removeCartaotoCart(itemId){
console.log("Remove "+itemId);
productSelected = ""; // Remove the product id from "memory"
$('#cartaoMensagemRemover'+itemId).hide();
$('#cartaoMensagem'+itemId).show();
//Ajax...
// In the success callback:
var button = $('#cartaoMensagemRemover'+itemId);
//$('#cartao').find(':button').attr('disabled',false); // The other buttons aren't disabled... This line is useless.
}

How to refresh a div on link or button click?

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>

DIV not being created from PHP when doing AJAX call

I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});

Call Javascript Function in PHP Echo

With reference to This link
, I am trying to delete rows dynamically from a table. Here's my Javascript function:
function deleteBox(id){
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
var dataString = 'id='+ id;
$("#flash_"+id).show();
$("#flash_"+id).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(result){
if(result){
$("#flash_"+id).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_"+id).slideUp(1000);
}else{
// Just hide data
$("#list_"+id).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
}
});
}
}
However, calling it from Echo in Php, doesn't seem to invoke it. Here's my PHP code:
echo "<td align=\"center\">" . $id."</td>";
echo "<td><a href = 'javascript:deleteBox($id)'>Delete</a></td>";
Please correct me wherever I'm goin wrong. An early help would be highly appreciated.
<td><a href = 'javascript:deleteBox($id)'>Delete</a></td>
to
echo "<td><a onClick='deleteBox(" . $id . ");'>Delete</a></td>";
In my opinion, thats how I would do it..
Edited and shortened the jscript;
function deleteBox(idDelete){
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
$("#flash_" + idDelete).show();
$("#flash_" + idDelete).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.post('delete.php', {'id': idDelete}, function(result) {
if(result){
$("#flash_" + idDelete).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_" + idDelete).slideUp(1000);
}else{
// Just hide data
$("#list_" + idDelete).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
});
}
in your delete.php:
$_POST['id']
to retrieve the ID.
Check this, Hope this helps. Instead of id, static values are given
<td align="center">1</td>
<td><a href='#' onclick='deleteBox(1)'>Delete</a></td>
echo "<td><a href='#' onclick='deleteBox(1)'>Delete</a></td>";
jsfiddle
I am updating the answer, check whether alert is working.
<script>
function deleteBox(a){
alert(a);
}
</script>
<?php
echo "<a href='#' onclick='deleteBox(1)'>Delete</a>";
?>
Since you're using jQuery, I wouldn't do the call to the function in the href. Try something like this:
Javascript:
$(function() {
$('.delete').click(function() {
var id = $(this).attr('data-id');
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
var dataString = 'id='+ id;
$("#flash_"+id).show();
$("#flash_"+id).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(result){
if(result){
$("#flash_"+id).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_"+id).slideUp(1000);
}else{
// Just hide data
$("#list_"+id).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
}
});
});
});
PHP/HTML:
echo "<td align=\"center\">" . $id."</td>";
echo "<td><a class='delete' data-id='" . $id . "'>Delete</a></td>";

twitter bootstrap modal vs. PHP POST request through javascript-ajax

why the code below doesn't do its job ?
I just need POST via javascript id content on click btn.
this code works properly in many other situations but not here that i'm using twitter bootstrap modal.
thanks.
<button id="<?php echo $id; ?>" class="btn btn-warning" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<span class="glyphicon glyphicon-trash"></span> delete id
</button>
<script type="text/javascript">
//delete id
$(document).on('click','.btn-warning',function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("are you sure ?")){
$.ajax({
type: "POST",
url: "page.php",
data: info,
success: function(){ window.location.href = "/logout.php"; }
});
}
return false;
});
</script>
PHP
if($_POST['id']){
$id=$_POST['id'];
$id = mysql_real_escape_string($id);
...
info = {'id' : del_id };
Try to send data as array.
First, I think you should be using isset(variable) in the PHP:
if (isset($_POST['ID'])
{
...
Second, it doesn't work because you need to set the data and a key -> value array.
data: {id: "ID_NUMBER"}
Look over the examples on Jquery's site: https://api.jquery.com/jQuery.ajax/
I would also suggest using a unique ID property or a new/unique class proverty, and then using that to add the onClick event.

Categories

Resources