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>";
Related
I want to remove the whole element on button click.
Removal must be done through Ajax technology, that is, without reloading the page.
After deleting a user, the entry with him should disappear from the list of all users.
Here is the structure of my code:
<?php
require_once "lib/mysql.php"; //database connection
$query = $pdo->prepare('SELECT * FROM `users`');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user) {
echo '<div class="infoAllUsers"><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].');">Delete</button></div>';
}; //display all users
?>
<script>
function deleteUser(id) {
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {'id': id},
success: function(data) {
$(this).closest(".infoAllUsers").remove();
}
});
}
</script>
There are no errors in js and php, there is nothing in the console, deletion from the database occurs correctly.
I am new to jQuery so I have tried some things like:
$(this).parent('div').remove();
$(this).closest('div').remove();
$(this).parent('.infoAllUsers').remove();
Take a different/cleaner approach
Set the id as a data attribute and assign a class, then add the click event to that.
<button class="delete" data-id="'.$user['id'].'">Delete</button>
$('.infoAllUsers .delete').click(function(elm) {
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {
'id': $(elm).data('id')
},
success: function() {
$(elm).parent().remove();
}
});
})
<?php
require_once "lib/mysql.php"; //database connection
$query = $pdo->prepare('SELECT * FROM `users`');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user) {
echo '<div class="infoAllUsers"><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].', this);">Delete</button></div>';
}; //display all users
?>
<script>
function deleteUser(id, this2) {
var $t = $(this2);
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {'id': id},
success: function(data) {
$t.closest('.infoAllUsers').remove();
}
});
}
</script>
The code seems correct, the only thing that occurs to me is that your php backend is not returning an Http code that is in the 2XX range and that is why it does not enter the success function of your ajax request, have you tried to make a console.log() inside the function that deletes the <div> to see if the JS reaches that point?
Jquery.ajax() function documentation
Having problem to change the state if its active or inactive everytime I clicked one of them nothings happened.
This is my code on ajax.
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).on('click','.status_checks',function(){
var status = ($(this).hasClass("btn-success")) ? '0' : '1';
var msg = (status=='0')? 'Deactivate' : 'Activate';
if(confirm("Are you sure to "+ msg)){
var current_element = $(this);
url = "ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:$(current_element).attr('data'),status:status},
success: function(data)
{
location.reload();
}
});
}
});
</script>
my php code ajax.php
<?php $db= new mysqli('localhost','root','password','dbname');
extract($_POST);
$user_id=$db->real_escape_string($id);
$status=$db->real_escape_string($status);
$sql=$db->query("UPDATE user SET status='$status' WHERE id='$id'");
echo 1;
?>
this is my code for displaying it, on this part everything works fine, when the value are 0 it will display inactive and 1 for active, however when clicking the status theres nothing happen only the notification and reload the page.
<td><i data="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' : 'Inactive'?>
</i></td>
Try to configure your code to:
$(document).on('click','.status_checks',function(){
var status = '1';
var msg = 'Activate';
if($(this).hasClass("btn-success")){
status = '0';
msg = 'Deactivate';
}
if(confirm("Are you sure to "+ msg)){
var id= $(this).data('id');
url = "/ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:id,status:status},
dataType: "json",
success: function(data)
{
console.log(data);
location.reload();
}
});
}
});
<?php $db= new mysqli('localhost','root','password','dbname');
$user_id=$_POST['id'];
$newStatus=$_POST['$status'];
$sql = "UPDATE user SET status=".$newStatus." WHERE id=".$user_id."
";
if($db->query($sql) === TRUE){
echo json_encode(1);
}else{
echo json_encode(0);
}
?>
<td><i data-id="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' :
'Inactive'?>
</i></td>
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.
}
my Php code;
$sql = "SELECT * FROM login_speak";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_assoc())
{
$tempArray[] = $row;
}
$resultArray = json_encode($tempArray);
echo $resultArray;
}
mysqli_close($con);
?>
my jquery code;
$.getJSON("url.php", function(data){
$("ul").empty();
$.each(data.result, function(){
$("ul").append("<li>Name:"+this['Name']+"</li>");
alert("kj");
});
});
I have done several things ,But nothing works.I php is correct and I have problem in script ,I guess.
Please give me the answer ,What wrong is done.
Thanks
json_encode from php can be accessed easily in a Javascript varible
There are many ways of doing this, however consider the simple way first if it works with the array you are sending.
in your example - assuming jquery:
var valu = [];
$.ajax(url: "url.php",
success: function(data){
valu=data;
});
see: http://www.dyn-web.com/tutorials/php-js/json/array.php
works for numeric and associative arrays.
I think you want change your code to something like this..
$.each(data.result, function(index,value){
$("ul").append("<li>Name:"+value.name+"</li>");
alert("kj");
});
Heres what I would do.
$.ajax({
url: "url.php",
type: "GET",
dataType: 'json'
}).done(function (data) {
$.each(codes, function(key,value){
$("ul").append('<option value="' + key + '">' + key + ' - ' + value + '</option>');
});
}).fail(function (jqXHR, textStatus, error) {
alert("error message");
console.log("error message: " + error);
});
I have a table loaded from a database and I want to be able to click and edit the row and have it update the database.
Currently it is not working and I have no idea why. What ways are there to troubleshoot this? How can I tell if the ajax is running? I am new to jquery and ajax, so I am not familiar with any debugging techniques that may be useful.
Here is the relevant code I have so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#fact_"+ID).hide();
$("#source_"+ID).hide();
$("#upvotes_"+ID).hide();
$("#downvotes_"+ID).hide();
$("#fact_input_"+ID).show();
$("#source_input_"+ID).show();
$("#upvotes_input_"+ID).show();
$("#downvotes_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var fact=$("#fact_input_"+ID).val();
var source=$("#source_input_"+ID).val();
var upvotes=$("#upvotes_input_"+ID).val();
var downvotes=$("#downvotes_input_"+ID).val();
var dataString = 'id='+ ID +'&fact='+fact+'&source='+source+'&upvotes='+upvotes+'&downvotes='+downvotes;
//var dataString = "'{'id':'"+ ID +"','fact':'"+fact+"','source':'"+source+"','upvotes':'"+upvotes+"','downvotes':'"+downvotes+"'}";
if(fact.length>0 && upvotes.length>0 && downvotes.length>0)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
alert("Success");
$("#fact_"+ID).html(fact);
$("#source_"+ID).html(source);
$("#upvotes_"+ID).html(upvotes);
$("#downvotes_"+ID).html(downvotes);
}
});
}
else
{alert('Enter something.');}
});
// Edit input box click action
$(".editbox123").mouseup(function()
{return false});
// Outside click action
$(document).mouseup(function(){
$(".editbox123").hide();
$(".text").show();
});
});
</script>
And table_edit_ajax.php is:
<?php
$con=mysqli_connect("XXXXXX","XXXXXX","XXXXXX","XXXXXX");
if (mysqli_connect_errno())
{echo "Failed to connect to MySQL: " . mysqli_connect_error();}
if($_POST['id'])
{
$id=mysqli_real_escape_string($_POST['id']);
$fact=mysqli_real_escape_string($_POST['fact']);
$source=mysqli_real_escape_string($_POST['source']);
$upvotes=mysqli_real_escape_string($_POST['upvotes']);
$downvotes=mysqli_real_escape_string($_POST['downvotes']);
$sql="UPDATE `FACTS` SET `fact_fact`='" .$fact . "', `fact_source`='" . $source . "', `fact_upvote_ctr`='" . $upvotes . "', `fact_downvote_ctr`='" . $downvotes . "' WHERE `fact_id`='" . $id . "';";
mysqli_query($con, $sql);
}
?>