I'm trying to get all checked checkbox values and parse them to my php functin using AJAX.
I use foreach to try and get each id of the checked checkbox's.
My problem is that when I try and update the database, it doesn't return '1' which I echo upon success.
When I take my foreach code out, it works.
My delete button is :
<form class="form -dark" id="form-inline" method="POST">
<div class="btn-group">
<button type="button" onclick="deleteSelectedTokens()" class="btn -dark" style="margin-left: 5px;" title="Delete all selected tokens"><i class="fa fa-trash"> </i></a>
</div>
</form>
My checkbox html/php code is :
<table class="table -dark -striped">
<thead>
<tr>
<th style="text-align: center;"><input type="checkbox" id="selectall"/></th>
<th style="text-align: center;">Token</th>
<th style="text-align: center;">Date/Time Generated</th>
<th style="text-align: center;">Status</th>
<th style="text-align: center;">Durbaility</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$username = $_SESSION['username'];
$token_result = mysqli_query($con, "SELECT id, token, used, time_generated, durability FROM tokens WHERE user_id = '$username' ORDER BY used");
if(mysqli_num_rows($token_result) > 0) {
while($token_row = mysqli_fetch_array($token_result)) {
$result = array($token_row['durability']); $sub_struct_month = ($result[0] / 30) ; $sub_struct_month = floor($sub_struct_month); $sub_struct_days = ($result[0] % 30); $sub_struct = "<i>".$sub_struct_month."</i> month(s) <i>".$sub_struct_days."</i> day(s)";
echo '
<tr style="text-align: center;">
<td>
<center><input type="checkbox" id="checkedTokens" class="checkbox" value='.($token_row['id']).'></center>
</td>
<td>
'.$token_row['token'].'
</td>
<td>
'.($token_row['time_generated']).'
</td>
<td>
'.($token_row['used'] == "0" ? "<span class='label label-primary'><i class='fa fa-check'></i> Valid </span>" : "<span class='label label-primary'><i class='fa fa-fa fa-times'></i> Used </span>").'
</td>
<td>
'.$sub_struct.'
</td>
';
} }else{ ?>
<tr>
<td colspan="12" style="padding: 30px;">
<div class="alert -dark">
<div class="alert-icon _text-danger">
<i class="fa fa-exclamation-circle"></i>
</div>
No tokens in your account
</div>
</td>
</tr>
<?php } ?>
</tr>
</tbody>
Notice I need to use foreach to get each check checkbox value so I can remove the selected ones when I press the delete button.
My AJAX send to PHP function is :
<script>
function deleteSelectedTokens() {
var selectedTokens = document.getElementById("checkedTokens").value;
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: selectedTokens
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
return false;
}
</script>
I think the problem is the Javascript... when I get the value of the checkboxes and post them, i think it's only getting 1 value inside the checkedTokens id.
My php receive code (this is not the problem) :
$username = $_SESSION['username'];
$selectedTokens = mysqli_real_escape_string($con, $_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
My console.log has not errors. Like I said, i think it's the javascript code for getting the value of my checkbox's not getting all the values.
You can send json of checked items:
<script>
var selectedTokens = [];
$('#checkedTokens:checked').each(function(key, value){
selectedTokens.push($(value).val());
});
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: JSON.stringify(selectedTokens)
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
</script>
And your php code mysqli_real_escape_string give only string we should convert json to get array:
$selectedTokens = json_decode($_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
In html it is not allowed to assign the same id to multiple tags. (As already mentioned in the comments.)
If you place your checkboxes on a <form id="some_id">, and give every checkbox a unique name and id, you can use the function $('#some_id').serialize() to get the data of the form and post it to the server.
Related
I am beginner on JSON. In my web application I am trying convert the table values into JSON and pass to another page using ajax call.
Below is my ajax query which I tried to convert the table values and pass to prescription.php page to save the records. There are two different separate java script variables which need to sent to the above page.
<script>
$(document).ready(function () {
$(document).on('click', '#submit', function () {
var getapt = $('#getapt').val();
var getpid = $('#getpid').val();
var ids={
'getapt': getapt,
'getpid': getpid,
}
var modess = $('#rows tr').map(function() {
let $tr = $(this);
return [{
"medname": $(this).find('.med_name').val(),
"morning": $(this).find('.morning').val(),
"noon": $(this).find('.noon').val(),
"night": $(this).find('.night').val(),
}]
console.log(modess);
});
var ids = JSON.stringify(ids);
var medical = JSON.stringify(modess);
$.ajax({
url: "adminquery/prescription.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{
index1: medical,
index2: ids
},
dataType:'json',
cache: false,
contentType: false,
processData: false,
async: false,
//contentType: "application/json; charset=utf-8",
})
});
});
</script>
Here is my prescription.php page
<?php
session_start();
require_once "../auth/dbconnection.php";
// if (isset(json_decode($_POST["data"])) {
$medical = json_decode($_POST["data"]);
if($stmt = mysqli_prepare($conn,"INSERT INTO prescription (apt_id,user_id,p_id, med_records,date) VALUES (?, ?, ?, ?, ?)")){
$user_id = $_SESSION['user_id'];
mysqli_stmt_bind_param($stmt, "sssss", $user_id);
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
// }else{
// echo "now records";
// }
mysqli_stmt_close($stmt);
?>
Here is my HTML codes.
<form method="post" id="prescriptionn" enctype="multipart/form-data">
<div class="table-responsive">
<table class="table table-bordered mb-0" id="medical">
<thead>
<tr>
<th>Medicine Name</th>
<th>Morning</th>
<th>Noon</th>
<th>Night</th>
<th> <button type="button" name="add" id="add" class="btn btn-success btn-xs">
+ </button> </th>
</tr>
</thead>
<tbody id="rows">
</tbody>
</table>
<br><br>
<div align="center">
<input type="hidden" value="<?php echo $row['apt_id'] ?>" id="getapt"
name="getapt" class="btn btn-primary">
<input type="hidden" value="<?php echo $row['p_id'] ?>" id="getpid" name="getpid" class="btn btn-primary">
<input type="button" name="submit" id="submit" class="btn btn-primary" value="Enter Prescription">
</div>
</div>
</form>
But nothing happen when I submit the button. Please give me some suggestions to improve my code may highly appreciated.
Following Method show how to send HTML table data using jQuery Ajax and save in Database. Hope this will help.
function storeTblValuesSpecial(x)
{
var TableData = new Array();
$('#'+x+''+' tr').each(function(row, tr){
TableData[row]={
"columOne" :$(tr).find('td:eq(1)').text()
, "columTwo" : $(tr).find('td:eq(2)').text()
, "columThree" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function storeTblValuesAjax(y) {
var TableData;
TableData = JSON.stringify(storeTblValuesSpecial(y));
$.ajax({
type: "POST",
url: '../yourFile.php',
data: {
"pTableData" : TableData
},
success: function(msg){
alert('Success');
}
});
}
<table id="table1" class="table table-dark" border="1">
<thead>
<tr>
<th scope="col">columOne</th>
<th scope="col">columTwo</th>
<th scope="col">columThree</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button type="button" class="btn-danger" id = "delete" onclick="storeTblValuesAjax('table1')" >Save Table</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
From PHP File once the Post Request Sent through Ajax Call
<?php
session_start();
// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);
// Decode the JSON array
$records = json_decode($tableData,TRUE);
$sizeOfArray = sizeof($records);
for($test = 1; $test < $sizeOfArray; $test++)
{
$columOne= str_replace(",","",$records[$test]['columOne']);
$columTwo= str_replace(",","",$records[$test]['columTwo']);
$columThree= str_replace(",","",$records[$test]['columThree']);
/* From Here a general SQL Insert query , pass $columOne , $columTwo , $columThree as the insert values, the loop will continue until the entire table is saved */
}
am using codeigniter, am working shopping cart. after selecting of items to cart using ajax jquery. Here, items menu and cart table will be side by side displayed.
Now, my task is to copying cart items to another table, by clicking button,which is done. now problem is on clicking button i need to copied and at a time i need to route to another page.. here i can copy cart items to another table but i can't redirect to another.for this i used jquery ajax.
now i need route to page which in views folder users/basket.php
Home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="row">
<div class="col-lg-12 text-center">
<?php if(isset($_SESSION['loggedin'])){?>
<div class="alert alert-success"><?php echo $_SESSION['loggedin'];?></div>
<?php } ?>
Hello, <?php echo $_SESSION['username']?>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<table class="table table-condensed table-hover">
<tr>
<th class="text-center">Item</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Add</th>
</tr>
<?php foreach($items as $item):?>
<tr class="success">
<td><?php echo $item['product_name'];?></td>
<td class="text-center"><input type="text" name="quantity" id="<?php echo $item['product_id'];?>" class="quantity" maxlength="2" size="2"></td>
<td><?php echo $item['product_price'];?></td>
<td><button type="button" name="add_cart" class="add_cart" data-productname="<?php echo $item['product_name'];?>" data-price="<?php echo $item['product_price'];?>" data-productid="<?php echo $item['product_id'];?>"><i class="fa fa-plus-circle"></i></button></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<div class="col-lg-6 col-lg-offset-1">
<div id="cart_details" class="text-center">
</div>
</div>
</div>
Product_controller.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller {
public function add(){
$this->load->library('cart');
$data = array(
'id' => $_POST["product_id"],
'name' => $_POST["product_name"],
'qty' => $_POST["quantity"],
'price' => $_POST["product_price"],
);
$this->cart->insert($data); //return rowid
echo $this->view();
}
public function load(){
echo $this->view();
}
public function remove(){
$this->load->library('cart');
$row_id = $_POST["row_id"];
$data = array(
'rowid' => $row_id,
'qty' => 0
);
$this->cart->update($data);
echo $this->view();
}
public function clear(){
$this->load->library('cart');
$this->cart->destroy();
echo $this->view();
}
public function view(){
$this->load->library('cart');
$output = '';
$output.='
<h3>Shopping cart</h3><br/>
<div class="table-responsive">
<div align="right">
<button type="button" id="clear_cart" class="btn btn-danger"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
<br/>
<table class="table table-bordered">
<tr>
<th class="text-center">Name</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Total</th>
<th class="text-center">Action</th>
</tr>';
$count = 0;
$content=$this->cart->contents();
foreach($content as $items){
$count++;
$output .='
<tr>
<td>'.$items["name"].'</td>
<td>'.$items["qty"].'</td>
<td>'.$items["price"].'</td>
<td>'.$items["subtotal"].'</td>
<td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'"><i class="fa fa-times" aria-hidden="true"></i></button></td>
</tr>';
}
$output .='
<tr>
<td colspan="4" align="right">Total</td>
<td>'.$this->cart->total().'</td>
</tr>
</table>
<button type="submit" name="basket" class="btn btn-danger btn-lg basket" ><i class="fa fa-shopping-cart" aria-hidden="true"></i></button>
</div>';
if($count == 0){
$output = '<h3>Cart is Empty</h3>';
}
return $output;
}
public function basket(){
if ($cart = $this->cart->contents()){
foreach ($cart as $item){
$order_detail = array(
'tblItemsID' => $item['id'],
'tblLoginID' => $this -> session -> userdata('user_id'),
'Qty' => $item['qty'],
'price' => $item['price'],
'total' => $item['subtotal']
);
$this->db->insert('tblShoppingCart', $order_detail);
}
}
}
}
Note:In product_controller.php i coded button to copy cart items to another table. on button click event i wrote in jquery ajax below
jquery Ajax:
<script>
$(document).ready(function(){
$('.add_cart').click(function(){
var product_id=$(this).data("productid");
var product_name=$(this).data("productname");
var product_price=$(this).data("price");
var quantity=$('#' + product_id).val();
if(quantity != '' && quantity >0)
{
$.ajax({
url:"<?php echo base_url();?>products/add",
method:"POST",
data:{product_id:product_id,product_name:product_name,product_price:product_price ,quantity :quantity},
success:function(data)
{
alert("Product Added into cart");
$('#cart_details').html(data);
$('#' + product_id).val('');
}
});
}
else
{
alert("Please Enter Quantity");
}
});
$('#cart_details').load("<?php echo base_url();?>products/load");
$(document).on('click','.remove_inventory',function(){
var row_id = $(this).attr("id");
if(confirm("Are you sure you want to delete item")){
$.ajax({
url:"<?php echo base_url();?>users/remove",
method:"POST",
data:{row_id:row_id},
success:function(data)
{
alert("Product remove fromm cart");
$('#cart_details').html(data);
}
});
}else{
return false;
}
});
$(document).on('click','#clear_cart',function(){
if(confirm("Are you sure you want to delete item"))
{
$.ajax({
url:"<?php echo base_url();?>products/clear",
success:function(data)
{
alert("Are you sure you want clear cart?");
$('#cart_details').html(data);
}
});
}
else{
return false;
}
});
$(document).on('click','.basket',function(){
if(confirm("Are you sure you want to delete item"))
{
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
window.location="users/basket";
}
});
}
else{
return false;
}
});
});
</script>
----------
Use this code on your needed redirect place:
where you will retrieve the response via ajax success response (date);
before that you will return the value in server side which mean controller.
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
location.href = data.url_path;
}
});
Use window.location.href
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
window.location.href="<?php echo base_url();?>users/basket";
}
});
after ajax success just write.
window.location.href="redirect_location_name";
I'm trying to remove row from my dynamic table. I've success to .append new row from JavaScript.
JavaScript
$(document).ready(function() {
// table #pos add-row
$(".add-row").keypress(function(e) {
if (e.which == 13) {
var barcode = $("#barcode").val();
$.ajax({
type: "post",
url: "production/ajax/load.php",
dataType: "json",
data: {
barcode: $("#barcode").val()
},
success: function(data) {
$("#pos tbody").append(data['content']);
}
});
}
});
// Find and remove selected table rows
$(".delete-row").click(function(){
alert('Success');
$("#pos tbody tr").remove();
});
})
load.php
<?php
if (isset($_POST['barcode'])) {
require '../controller/connection/connection-management.php';
$barcode = $_POST['barcode'];
$status = false;
$sql = "SELECT code, title, wri_name, pub_name, year, main_category.main_category, category.category, call_number, pusat_penerbit, mrican, paingan, selling_price, discount FROM product, writer, publisher, main_category, category WHERE product.writer = writer.writer AND product.publisher = publisher.publisher AND product.main_category = main_category.main_category AND product.category = category.category AND code = '{$barcode}' ORDER BY title";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
while($row = mysqli_fetch_assoc($result)) {
$barcode = $row['code'];
$title = $row['title'];
$sellingPrice = number_format($row['selling_price'], 0, ',', '.');
$quantity = 1;
$discount = $row['discount'];
$total = number_format((($row['selling_price'] - ($row['selling_price'] * ($discount / 100))) * $quantity), 0, ',', '.');
$append = "<tr class='pointer'>
<td align='right'><a href='javascript:;' class='delete-row'><i class='fa fa-trash'></i></a></td>
<td><small>{$barcode}</small></td>
<td><div style='text-align: justify'><strong>{$title}</strong></div></td>
<td align='right'>{$sellingPrice}</td>
<td align='center'><input id='quantity' type='text' class='form-control' style='text-align:center' value='1'></td>
<td align='center'><input type='text' class='form-control' style='text-align:center' value='{$discount}'></div></td>
<td align='right'>{$total}</td></td>
</tr>";
}
$status = true;
}
$data = array(
"status" => $status,
"content" => $append
);
echo json_encode($data);
}
?>
pos.php it's html table
<div class="x_title">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="delete-row btn btn-primary"><i class="fa fa-pencil-square-o"></i></button>
</span>
<input name="barcode" id="barcode" type="text" class="add-row form-control" placeholder="Enter item name or scan barcode">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Receive</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li>Receive</li>
<li>Return</li>
<li>Purchase Order</li>
<li>Transfer</li>
<li>Store Account Payment</li>
</ul>
</div>
</div>
</div>
<div class="x_content">
<div class="table-responsive">
<table name="pos" id="pos" class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th style="text-align:center" class="column-title col-sm-7" colspan="3">Item Name </th>
<th style="text-align:right" class="column-title col-sm-1">Cost </th>
<th style="text-align:center" class="column-title col-sm-2">Qty. </th>
<th style="text-align:center" class="column-title col-sm-1">Disc % </th>
<th class="column-title col-sm-1" style="text-align:right">Total </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
So when I add new row in the table, everything works fine like this picture:
But when I click trash icon with class='delete-row', that's is not working. So I think, when I append data to table tbody it's not read class or id from the new row.
Please someone help. I can't find any similar questions like mine. I just want to know, how to remove table row when I click trash icon from JavaScript.
You have two issues here (which is why I have not voted to close as a duplicate). Firstly you need to use a delegated event handler on the .delete-row element as it is appended to the DOM after load. Your current code does nothing as you attempt to attach the event handler before the element exists.
Secondly, you need to use DOM traversal to remove only the parent tr of the clicked button. At the moment your code would remove all rows. Try this:
$('#pos').on('click', '.delete-row', function() {
$(this).closest('tr').remove();
});
Did you tried delegate?
$(document).delegate('.delete-row', 'click', function(){
//your remove code here
});
You can also use on (for jquery versions 1.7.1+)
$(document).on('click', '.delete-row', function(){
//your remove code here
});
I have an array of rows, each with a radio button with the same name (name='status'). I have put the radio buttons into an index so that each radio button will reflect its correct value. However, the javascript no longer works to change the value - I am stumped with the corresponding changes I need to make to the javascript.
<form action="<?php echo $this->form_action; ?>" method="post">
<p class="hide"><input name="status" type="text" value="" /></p>
<table id="manage-items" cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<th><?php echo $this->translate('Item');?></th>
<th><th><?php echo $this->translate('Status');?></th></th>
</tr>
</thead>
<tbody>
<?php $ind = 0; ?>
<?php foreach ($this->items as $item) {
$item_link = 'type=product';
?>
<tr id="item_<?php echo $ind; ?>">
<td data-label="Title"><span class="orangelink"><?php echo $item->title; ?></span></td>
<td align="left" style="padding-left:22px" class="color-status-<?php echo $item['active']; ?>">
<?php if (in_array($item['active'], array(0, 1))) { ?>
<input type="radio" name="item[<?php echo $ind; ?>][status]" value="1" <?php if ($item['active'] == 1) echo 'checked'; ?>>Active
<br>
<input type="radio" name="item[<?php echo $ind; ?>][status]" value="0" <?php if ($item['active'] == 0) echo 'checked'; ?>>Inactive
<?php } else { ?>
<?php echo $item['active']; ?>
<?php } ?>
</td>
</tr>
<?php $ind++; ?>
<?php } ?>
</tbody>
</table>
</form>
<script type="text/javascript">
//console.log(jQuery)
head.ready('jquery', function () {
$(document).ready(function () {
$('input[name="radio"]').click(function () {
var status = this.value;
var id = $(this).parents('tr').attr('id');
console.log('here now')
$.ajax({
type: 'post',
url: "?module=items&controller=block&action=modDaStatusBro",
data: 'id=' + id + '&status=' + status,
beforeSend: function () {
$('#' + id).animate({
'backgroundColor': '#FFBFBF'
}, 400);
},
success: function (result) {
if (result == 'ok') {
$.get(window.location.href, function (data) {
$('#' + id).html($(data).find('#' + id).html());
setTimeout(function () {
$("#" + id + "").animate({'backgroundColor': 'transparent'}, 400).find('.tooltip').simpletooltip();
deletePage();
}, 500);
});
} else {
alert(result);
$("#" + id + "").animate({'backgroundColor': 'transparent'}, 400);
}
}
});
});
});
});
</script>
Table data elements generated in PHP between
<tr id="<?php echo $item['id']; ?>">
....
</tr>
do not appear to contain input elements named "status". The HTML generated for each value of $ind is expected to be
<input type="radio" name="item[n][status]" .... Active
<input type="radio" name="item[n][status]" .... Inactive
where n is the value of $ind. But the selector in
$('input[name="status"]').click(function () {
doesn't match the name format. A one key stroke solution would be to to add a * wild card to the selector to match "status" anywhere in the name value:
$('input[name*="status"]').click(function () {
Other possibilities exist such as adding a special class name to each radio button affected (not recommended), or add a special data attribute to each radio input to be found by query selector (feasible).
Footnote: DIV elements surrounding TR elements should not be there. DIV is not listed as a permitted child element of TBODY elements, nor a permitted parent object of TR elements.
(Answer to comment)
A jQuery plugin is needed for color animation of properties, e.g. backgroundColor.
Code can be downloaded from CDNs at
https://code.jquery.com/color/jquery.color-2.1.2.min.js , or
https://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.min.js
or the entire package can be downloaded from GitHub
How Delete row in table html using ajax and php,
I need delete row in html table select row and click button delete make delete using ajax Currentally can make delete without ajax but I need delete row and stay on page without make submit on other page
code javaScript
function getDelete()
{
$.ajax({
type:"post",
//dataType:"json",
data:"id="+id,
url:"delete_address.php?id=$id", // url of php page where you are writing the query
success:function(json)
{
},
error:function(){
}
});
}
code html and php
<?php
$resualt=mssql_query("SELECT * FROM Address where user_id='$UserId' ") ;
echo "<table border='1' class='imagetable' id='imagetable'
width='400px' >\n";
echo '<thead>'.'<tr>';
echo '<th>Street</th>'.'<th>Quarter</th>'.
'<th>From</th>'.'<th>To</th>'.'<th>Notes</th>';
echo '</tr>'.'</thead>';
echo '<tbody>';
while ($row = mssql_fetch_assoc($resualt)) {
$fromDate=$row['from_date'];
$toDate=$row['to_date'];
echo " <tr onClick='myPopup($row[id])'".
( $_GET['id'] == $row['id'] ?
"style='background-color: green;'":"").">\n"."<td >
{$row['street']} </td>\n".
"<td>{$row['quarter']}</td>\n"."<td>$fdate2</td>\n".
"<td>$tdate2</td>\n"."<td>{$row['other_info']}</td>\n";
}
echo '</tbody>';
echo "</table>\n";
?>
<?php
echo"<a class='button-link' onClick='getDelete()'>delete</a>";
?>
code sql query
<?php
$idEmploye=$_GET['id'];
$userId=$_GET['user_id'];
$db_host = 'MOHAMMAD-PC\SQL2005';
$db_username = 'sa';
$db_password = '123321';
$db_name = 'db_test';
mssql_connect($db_host, $db_username, $db_password);
mssql_select_db($db_name);
mssql_query("DELETE FROM Address
WHERE id='$idEmploye' ; ") or die(mssql_error()) ;
echo '<script language="javascript">';
echo 'alert("successfully deleted ")';
echo '</script>';
echo "<script>setTimeout(\"location.href ='address.php';\",10); </script>";
?>
Any Help Very Thanks
Try this solution
HTML:
<table>
<tr>
<td>Username</td>
<td>Email</td>
<td>Action</td>
</tr>
<tr>
<td>TheHalfheart</td>
<td>TheHalfheart#gmail.com</td>
<td>
<input type="button" class="delete-btn" data-id="1" value="Delete"/>
</td>
</tr>
<tr>
<td>freetuts.net</td>
<td>freetuts.net#gmail.com</td>
<td>
<input type="button" class="delete-btn" data-id="2" value="Delete"/>
</td>
</tr>
</table>
We have two button's properties call data-id and class delete-btn
AJAX jQuery:
<script language="javascript">
$(document).ready(function(){
$('.delete-btn').click(function(){
// Confirm
if ( ! confirm('Are you sure want to delete this row?')){
return false;
}
// id need to delete
var id = $(this).attr('data-id');
// Current button
var obj = this;
// Delete by ajax request
$.ajax({
type : "post",
dataType : "text",
data : {
id : id
},
success : function(result){
result = $.trim(result);
if (result == 'OK'){
// Remove HTML row
$(obj).parent().parent().remove();
}
else{
alert('request fails');
}
}
});
});
});
</script>
In PHP:
Get the ID and delete
Reponse OK if success
Sorry i'm learning English, please fix if its bad