show hide button jquery with dynamic values - php

i have this code in index.php:
<tbody>
<?php foreach($data as $fetch): ?>
<tr>
<input type="hidden" name="user_id" value="<?php echo $_SESSION['user_id']?>">
<td class="segment" contenteditable="true"><?= $fetch['segment'] ?></td>
<td class="text-center">
<button class = "btn btn-default action-btn" data-id="<?= $fetch['id'] ?>" data-action="update">
<span class = "glyphicon glyphicon-edit"></span> Update
</button>
|
<button class = "btn btn-success activate-btn action-btn" data-id="<?= $fetch['id'] ?>" type="submit" data-action="activate">
<span class = "glyphicon glyphicon-check"></span> Activate
</button>
<button style="display:none" class = "btn btn-danger deactivate-btn action-btn " data-id="<?= $fetch['id'] ?>" data-action="deactivate">
<span class = "glyphicon glyphicon-folder-close"></span> deactivate
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<form action="create.php" method="post" class="form-inline">
<div class = "form-group">
<label>Segment:</label>
<input type = "text" name = "segment" class = "form-control" required = "required"/>
</div>
<div class = "form-group">
<button type="submit" name = "save" class = "btn btn-primary"><span class = "glyphicon glyphicon-plus"></span> Add</button>
</div>
</form>
<script type="text/javascript">
$(".action-btn").on("click", function(e) {
var id = $(this).attr("data-id");
var segment = $(this).parents("tr").find("td.segment").html();
var action = $(this).attr("data-action");
$.ajax({
"url": "action.php",
"method": "post",
"data": {
"id": id,
"segment": segment,
"action": action
},
success: function(data) {
alert(data);
}
});
}); </script>
<script>$(".activate-btn").click(function(){$(this).hide();$(".deactivate-btn").show();});</script>
</body>
the problem is when i click on any activate button all deactivate button show up and the activate doesnt disappear,
i mean in any when i click activate the deactivate sho up in every other td and when i click deactivate again the activate button doesnt show up, any help?

You may want to change
$(".activate-btn").click(function(){$(this).hide();$(".deactivate-btn").show();});
into:
$(".action-btn").click(function(){$(this).hide();$(".deactivate-btn").show();});
$(".deactivate-btn").click(function(){$(this).show();$(".action-btn").show();});

Having 2 buttons is abit confusing to the end user since they wont know which segment is active and which segment is deactivated. From your code,all the buttons are shown when the page loads initially. An alternative would be:
if($fetch['status']=="active"){
<button class="btn-danger statusbtn" data-action="deactivate"
id="<?=$fetch['id']?>">
<span class="glyphicon glyphicon-folder-close"></span>
Deactivate
</button>
}else{
<button class="btn-success statusbtn" data-action="activate"
id="<?=$fetch['id']?>">
<span class="glyphicon glyphicon-ok"></span>
Activate
</button>
}
Then edit your javascript to read:
<script type="text/javascript">
$(".action-btn").on("click", function(e) {
var id = $(this).attr("id");
var segment = $(this).parents("tr").find("td.segment").html();
var action = $(this).attr("data-action");
$.ajax({
"url": "action.php",
"method": "post",
"data": {
"id": id,
"segment": segment,
"action": action
},
success: function(data) {
if(action=='activate'){
$(this).html("
<span class='glyphicon glyphicon-folder-close'>
</span>
Deactivate");
$(this).attr('data-action',"deactivate");
$(this).removeClass('btn-success')
$(this).addClass('btn-danger');
}else{
$(this).html("
<span class='glyphicon glyphicon-ok'>
</span>
activate");
$(this).attr('data-action',"activate");
$(this).removeClass('btn-danger')
$(this).addClass('btn-success');
}
alert(data);
}
});
});
</script>
I haven't run the code to test it for errors but i think this will solve your problem.

Related

status update on nested statement partially working

Please I need help to figure out why my code below isn't working. I'm not very good at PHP and ajax to start with but find it difficult to figure out why the code below wouldn't function properly.
What it does: changes data in database to 'Disable' but to update to 'Enable' on-click wouldn't work. Please help!
status.php
<?php
session_start();
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="User"){
header('location:index.php');
}
$select=$pdo->prepare("select * from tbl_user order by userid desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ) ){
if (isset($_POST['ridd'])){
$id=$_POST['ridd'];
if($row->user_status == 'Enable'){
$status_str="Disable";
$sql="UPDATE `tbl_user` SET `user_status` = ? WHERE userid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$status_str, $id]);
}else if($row->user_status == 'Disable'){
$status_str2="Enable";
$sql="UPDATE `tbl_user` SET `user_status` = ? WHERE userid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$status_str2, $id]);
}else{
echo'Internal loop error in Updating';
}
}
}
registration.php
<script>
$(document).ready(function() {
$('.switch').click(function() {
var tdh = $(this);
var id = $(this).attr("id");
swal({
title: "Do you want to Change user status?",
text: "Once changed, it can be reversed!",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
$.ajax({
url: 'status.php',
type: 'POST',
data: {
ridd: id
},
success: function(data) {
//tdh.parents('tr').load;
}
});
swal("User status has been changed!", {icon: "success",});
window.location.reload(true);
} else {
swal("No action performed!");
window.location.reload(true);
}
});
});
});
</script>
here is my table code in registration.php
<tbody>
<?php
$select=$pdo->prepare("select * from tbl_user order by userid desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ) ){
$status='Disable';
$colour="btn-danger";
if($row->user_status == 'Enable'){
$status='Enable';
$colour="btn-success";
}
echo'
<tr>
<td>'.$row->userid.'</td>
<td>'.$row->username.'</td>
<td>'.$row->user_status.'</td>
<td>
<div id='.$row->userid.' class="switch">
<button type="button" class="btn '.$colour.'">'.$status.'</button>
</div>
</td>
<td>
<button id='.$row->userid.' class="btn btn-danger btndelete" ><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
';
}
?>
</tbody>
When I click on button 'switch', I'm able to perform a toggle function so that it can update either 'Enable' or 'Disable' on my database. At the moment, only the disable is working and I have to manually enable the user from the database (phpmyadmin).
You can check if the button which is clicked has class btn-success if yes then now we need disable it or else enable so send this as well in your ajax call and at your backend get it using $_POST["status"] and update same . Also, you don't need to reload page instead inside your success function of ajax just change the button using .html().
Demo code :
$(document).ready(function() {
$('.switch').click(function() {
var tdh = $(this);
var id = $(this).attr("id");
swal({
title: "Do you want to Change user status?",
text: "Once changed, it can be reversed!",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
var button_status = $(this).find("button").hasClass("btn-success") ? "Disable" : "Enable"; //check if button has success means we need disable it now else enable .
/*$.ajax({
url: 'status.php',
type: 'POST',
data: {
ridd: id,
status: button_status //send to chnage
},
success: function(data) {*/
//if disable
if (button_status == "Disable") {
$("#" + id).html("<button type='button' class='btn btn-danger '>Disable</button>") //put enable button
tdh.closest("tr").find("td:eq(2)").text("Disable")
} else {
$("#" + id).html("<button type='button' class='btn btn-success '>Enable</button>") //disable buttn
tdh.closest("tr").find("td:eq(2)").text("Enable")
}
/* }
});*/
swal("User status has been changed!", {
icon: "success",
});
} else {
swal("No action performed!");
}
});
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>
<table class="table">
<tbody>
<tr>
<td>1</td>
<td>sw</td>
<td>Enable</td>
<td>
<div id='1' class="switch">
<button type="button" class="btn btn-success ">Enable</button>
</div>
</td>
<td>
<button id='1' class="btn btn-danger btndelete"><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
<tr>
<td>2</td>
<td>sw</td>
<td>Disable</td>
<td>
<div id='2' class="switch">
<button type="button" class="btn btn-danger ">Disable</button>
</div>
</td>
<td>
<button id='2' class="btn btn-danger btndelete"><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
</tbody>
</table>

Ajax Jquery form submit

Hello I am running a form using ajax submit functions using PHP and JS
bellow is my code
submit.php
<?php
if(isset($_POST['add_data'])){
echo "add id";
}
if(isset($_POST['update_data'])){
echo "update_id";
}
?>
Form.js
$('form.data').on('submit',function(){
var info = $(this),
url = info.attr('action'),
method = info.attr('method'),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
form.php
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button name="add_data" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>
<button name="update_data" value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
however the result I am getting is not correct if I click one of the button the console replies:
add idupdate_id
instead of one of the following
add id
or
update_id
On submit you are going to have the value set so isset will always return true. What you must do is:
if(!empty($_POST['add_data'])){
echo "add id";
}
The problem is that your form contains both add_data and update_data, so they will be always set in $_POST. If you want different action for each button, you could assign a function to the onClick event to both buttons, check which caused the event and pass it to your AJAX data.
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button name="add_data" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>
<button" name="update_data" value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
Then in your JS:
$("button").click(function(){
var info = $(this),
url = info.attr('action'),
method = info.attr('method'),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
data["action"] = ($(this).attr("name") === "add_data") ? 0 : 1; //If add_data -> 0 else -> 1
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
And then in your PHP, you look for $_POST["action"] variable
if($_POST["action"] == 0) {
echo "add_data";
} else {
echo "update_data";
}
EDIT: If you would like to, you don't have to check it in a condition, and just past the name attribute to data["action"] and then check in PHP, if $_POST["action"] is equal to add_data or update_data
Use next code for separating your button actions:
HTML:
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button value="add" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>Add</button>
<button value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
JS:
$('form.data > button').on('click',function(){
var info = $(this).parent(),
url = info.attr('action'),
method = info.attr('method'),
task = $(this).val(),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
data['task'] = task;
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
PHP:
if(isset($_POST['task']) && $_POST['task'] == 'add'){
echo "add id";
}
if(isset($_POST['task']) && $_POST['task'] == 'update'){
echo "update_id";
}

How to remove or fadeout selected div parta after success by jquery

I want to remove selected div part by click on cancel button php code
while($fetch_user_info= mysqli_fetch_assoc($query_client))
{
<div class="col-sm-12 m-t-20 insight_box">
<button type="button" class="btn btn-default btn-sm cancel_insights" value="<?php echo $c_id;?>">Cancel</button>
<button type="button" class="btn btn-info btn-sm " onclick="window.open('<?php echo $url.'?pan='.$jh1_pan ?>', '_blank')">Yes, On board now!</button>
</div>
}
?>
Jquery :
$('.cancel_insights').click(function() {
var c_id = $(this).val();
$.post('url', {
'c_id': c_id,
'action': 'action'
}, function(data, status) {
if (data == 'true') {
$(this).find('.insight_box').fadeOut();
}
});
});
change
$(this).find('.insight_box').fadeOut();
into this
$(this).parent().fadeOut();
You could add an event so when the button is clicked it gets its parent and removes it, like so
$(".cancel_insights").click(function() {
$(this).parent().remove();
});

jquery button click event isn't working on dataTable

After adding any row in dataTable, edit or delete button click isn't working. I have done this with ajax. in success function i have destroyed the dataTable. Then load all the data and initiate the dataTable. My codes are following.
HTML Code:
<table class="table table-striped table-bordered bootstrap-datatable datatable">
<button class="btn btn-success" title="Add Items" id="addCalzone"><i class="halflings-icon white plus"></i> Add Item</button><br/><br/>
<thead>
<tr>
<th>No.</th>
<th>Name</th>
<th>Price</th>
<th>
<div class="text-center">
Action
</div>
</th>
</tr>
</thead>
<tbody class="dataTable-tbody">
<?php foreach($row as $key => $r): ?>
<tr class="tableRow" data-id="<?= htmlentities(stripcslashes($r['id']), ENT_QUOTES, 'UTF-8'); ?>">
<td></td>
<td><?= htmlentities(stripcslashes($r['name']), ENT_QUOTES, 'UTF-8'); ?></td>
<td> $ <?= htmlentities(stripcslashes($r['price']), ENT_QUOTES, 'UTF-8'); ?></td>
<td>
<div class="text-center">
<button class="btn btn-info editCalzone" title="Edit"><i class="halflings-icon white edit"></i> Edit</button>
<button class="btn btn-danger dltCalzone" title="Delete"><i class="halflings-icon white trash"></i> Delete</button>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="modal hide fade" id="addItem">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1>Calzone</h1>
</div>
<div class="modal-body">
<h3>Name</h3>
<input type="text" id="itemName" value="" required="required" />
<input type="hidden" id="type" value="add"/>
<h3>Price</h3>
<input type="number" min="0" step="0.01" value="" required="required" id="itemPrice" />
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="addClose" data-dismiss="modal">Close</button>
<button class="btn btn-success" id="addbtn">Save</button>
</div>
</div>
Javascript Code:
function initDataTable(){
$('.datatable').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span12'i><'span12 center'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
} );
$('.btn-close').click(function(e){
e.preventDefault();
$(this).parent().parent().parent().fadeOut();
});
$('.btn-minimize').click(function(e){
e.preventDefault();
var $target = $(this).parent().parent().next('.box-content');
if($target.is(':visible')) $('i',$(this)).removeClass('chevron-up').addClass('chevron-down');
else $('i',$(this)).removeClass('chevron-down').addClass('chevron-up');
$target.slideToggle();
});
$('.btn-setting').click(function(e){
e.preventDefault();
$('#myModal').modal('show');
});
}
$('#addbtn').click(function(){
var $add = {
name : $('#itemName').val(),
cost : $('#itemPrice').val(),
type : $('#type').val()
};
if($add.name == '' || $add.cost == ''){
alert('Both fields must be filled');
}else{
$.ajax({
type: 'POST',
dataType: 'json',
url: $calzone.submitURL,
data: {
calzoneName: $add.name,
calzoneCost: $add.cost,
calzoneAction: $add.type
},
cache: false,
error: function(){
alert('An Error Occured !!');
},
success: function(response){
alert('Successfully Saved !!');
$('#itemName').val('');
$('#itemPrice').val('');
$('#type').val('');
$('.datatable').DataTable().destroy();
$('.dataTable-tbody').html('');
for(i=0; i<response.length; ++i){
var content = '<tr class="tableRow" data-id="' + response[i].id + '">' +
'<td>' + (i+1) + '</td>' +
'<td>' + response[i].name + '</td>' +
'<td>' + response[i].price + '</td>' +
'<td>' +
'<div class="text-center">' +
'<button class="btn btn-info editCalzone" title="Edit"><i class="halflings-icon white edit"></i> Edit</button> ' +
'<button class="btn btn-danger dltCalzone" title="Delete"><i class="halflings-icon white trash"></i> Delete</button>' +
'</div>' +
'</td>' +
'</tr>';
$('.dataTable-tbody').append(content);
}
initDataTable();
$('#addItem').modal('hide');
}
});
}
});
$('.editCalzone').click(function(){
$('#addItem').modal('show', {
backdrop: 'static'
});
var $edit = {
name : $(this).closest('tr').find('td').eq(1).text(),
price : $(this).closest('tr').find('td').eq(2).text().split(' ')[2],
type : $(this).closest('tr').data('id')
};
$('#itemName').val($edit.name);
$('#itemPrice').val($edit.price);
$('#type').val($edit.type);
});
$('.dltCalzone').click(function(){
var $dlt = {
confirm : confirm("Are you want to delete the selected item ?"),
key : $(this).closest('tr').data('id')
};
if($dlt.confirm){
$.ajax({
type: 'POST',
url: $calzone.submitURL,
data: {
deleteKey : $dlt.key
},
error: function(){
alert('An Error Occured');
},
success: function(){
alert('Data has been deleted !!');
location.reload();
}
});
}else{
alert('Your data is safe !');
}
});
The response from the server is perfect. There is no error. But after adding a row or editing a row's information, Edit and Delete button isn't working. But It's working after reload the page. What is the problem in the dataTable initialization, i can't figure out. Please help me to figure out the problem and solve it.
replace your
$('.editCalzone').click(function(){
$('.dltCalzone').click(function(){
with
$(document).on('click', '.editCalzone', function(){
$(document).on('click', '.dltCalzone', function(){

Remove Label Tag / Add Input textBox Using Jquery/Bootstrap

I have a column in Database with name URL and ID(PK) i'm using PHP/MYSQL
Im displaying values from db now i want to perform EDIT(update) operation Using Jquery/Ajax.
When i click on Edit link it is replaced with Update/Cancel links Which is working fine and im able to perform update operations.
My requirement is when i click on edit Url data which im using lable tag should replace with input textbox and i should perform update operation
HTML Code
<div class='col-md-4'>
<label class="feed_label" id="feed_label" idl='<?php echo $row->id;?>'><?php echo $row->url; ?></label>
<input name="url1" class="form-control url1 feed_text" value="<?php echo $row->id;?>" id="url1" type="text" placeholder="enter url" style="display:none;">
</div>
<div class='col-md-2'>
<a ide='<?php echo $row->id;?>' id="edit" class='edit' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update btn btn-primary btn-sm' href='#' style='display:none;'>UPDATE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancel btn btn-warning btn-sm' href='#' style='display:none;'>CANCEL</a>
</div>
JQUERY CODE
JQUERY CODE
//EDIT,DELETE TO UPDATE,CANCEL
$('body').delegate('#edit','click',function(){
//alert();
$(this).siblings('#delete').hide();
$(this).siblings('#update,#cancel').show();
$(this).hide();
$('#feed_label').removeClass('feed_label').addClass('feed_url');
});
$('body').delegate('#cancel','click',function(){
//alert();
$(this).siblings('#edit,#delete').show();
$(this).siblings('#update').hide();
$(this).hide();
$("#update_url")[0].reset();
});
//ENDS
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
//alert(IdEdit);
//return false;
$.ajax({
url:"pages/feeds.php",
type:"post",
datatype:"json",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
//alert('success');
$('#id').val(show.id);
$('#url1').val(show.url);
//$('#add_feed_form')[0].reset();
//$('#showdata').load('pages/feeds.php');
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
//alert('update');
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
//alert();
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
//alert('updated');
$('input[type=text]').val('');
showdata();
$('#add_feed_form')[0].reset();
$('#showdata').load('pages/feeds.php');
}
});
});
//UPdate Ends
PHP Code
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
//Ends
Any help Is appreciated Thanks!!
Here i give sample for your case :
HTML
<div class="container">
<label>John</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
<hr/>
<div class="container">
<label>John Who</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
JS (you can simplified below code into one handler)
$(document).on('click', '.edit', function(e){
var data = $(this).prev();
if ( data.is('label') ) data.replaceWith('<input value="'+data.text()+'">');
});
$(document).on('click', '.delete', function(e){
var data = $(this).prev().prev();
if ( data.is('input') ) data.replaceWith('<label>'+data.val()+'</label>');
});
DEMO

Categories